Reputation: 63
I have an issue in the code snippet below:
I have a list of list, some of which is empty. First I want to replace the empty value with a value and then flatten it.
Here's the code snippet:
a = [['3'] , ['4'], [], ['6']] #I want to get ['3', '4', 0 , 6]
flat = ['0' if i == '[]' else i for element in a for i in element]
But I'm unable to get the result. Kindly help
Upvotes: 0
Views: 1058
Reputation: 513
Here is another way to flatten it to a 1-dimensional array, but it doesn't replace the empty array as 0.
from itertools import chain
a = [
['3'],
['4'],
[],
['6']
]
flatten_list = list(chain.from_iterable(a))
print(flatten_list)
Upvotes: 0
Reputation: 151
Try the below code,
Code1 -
a = [['3'] , ['4'], [], ['6']] #I want to get ['3', '4', 0 , 6]
updated = [val[0] if val else '0' for val in a]
print(updated)
Code2 (For understanding purpose in a long form) -
a = [['3'] , ['4'], [], ['6']] #I want to get ['3', '4', 0 , 6]
for i in range(len(a)):
if a[i] == []:
a[i] = '0'
else:
a[i] = a[i][0]
print(a)
Both the above code fulfills your requirment.
Upvotes: 1
Reputation: 43300
You can use next with a default value
flat = [next(x, "0") for x in a]
or just the fact that an empty list is falsy
flat = [x[0] if x else "0" for x in a]
Upvotes: 3