从字符串列表中提取数字 - python

时间:2012-03-15 00:42:56

标签: python list-comprehension

如果我有一个像[ [100], [500], [300] ]这样的列表,python中从中提取数字的最佳方法是什么?

result = [ 100, 500, 300 ]

2 个答案:

答案 0 :(得分:3)

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

#or
from itertools import chain
y = list(chain.from_iterable(x))

答案 1 :(得分:2)

来自this question

l=[[100], [500], [300]]
result=[item for sublist in l for item in sublist]

来自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是你的朋友......