If I have a list like this [ [100], [500], [300] ]
, what's the best way in python to extract the numbers from it?
result = [ 100, 500, 300 ]
If I have a list like this [ [100], [500], [300] ]
, what's the best way in python to extract the numbers from it?
result = [ 100, 500, 300 ]
x = [ [100] , [500] , [300] ]
y = [ i[0] for i in x]
#or
from itertools import chain
y = list(chain.from_iterable(x))
From this question:
l=[[100], [500], [300]]
result=[item for sublist in l for item in sublist]
From wikibooks:
def flatten(seq, list = None):
"""flatten(seq, list = None) -> list
Return a flat version of the iterator `seq` appended to `list`
"""
if list == None:
list = []
try: # Can `seq` be iterated over?
for item in seq: # If so then iterate over `seq`
flatten(item, list) # and make the same check on each item.
except TypeError: # If seq isn't iterable
list.append(seq) # append it to the new list.
return list
Google is your friend ...