1

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 ]
hochl
  • 12,524
  • 10
  • 53
  • 87
Vanddel
  • 1,094
  • 3
  • 13
  • 32

2 Answers2

3
x = [ [100] , [500] , [300] ]
y = [ i[0] for i in x]

#or
from itertools import chain
y = list(chain.from_iterable(x))
kev
  • 155,172
  • 47
  • 273
  • 272
2

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 ...

Community
  • 1
  • 1
hochl
  • 12,524
  • 10
  • 53
  • 87