How to extract non-empty elements from python for number list
Question:
I currently have a list that looks like this:
[
[0], [2], [4], [6], [7], [9], [20], [24],
[], [26], [], [27], [], [], [], [],
[], [], [], [], [], [], [], [],
[], []
]
How can I transform it to look like [0, 2, 4, 6, 7, 9, 20, 24, 26, 27]
?
Answers:
Assuming list1
the input list, use itertools.chain
:
from itertools import chain
out = list(chain.from_iterable(list1))
output: [0, 2, 4, 6, 7, 9, 20, 24, 26, 27]
Just use a list comprehension:
out = [l[0] for l in list1 if len(l) > 0]
I currently have a list that looks like this:
[
[0], [2], [4], [6], [7], [9], [20], [24],
[], [26], [], [27], [], [], [], [],
[], [], [], [], [], [], [], [],
[], []
]
How can I transform it to look like [0, 2, 4, 6, 7, 9, 20, 24, 26, 27]
?
Assuming list1
the input list, use itertools.chain
:
from itertools import chain
out = list(chain.from_iterable(list1))
output: [0, 2, 4, 6, 7, 9, 20, 24, 26, 27]
Just use a list comprehension:
out = [l[0] for l in list1 if len(l) > 0]