2012-03-15 138 views
1

如果我有一個像這樣的列表[ [100], [500], [300] ],python中從數字中提取數字的最佳方法是什麼?從字符串列表中提取數字 - python

result = [ 100, 500, 300 ] 
+0

哪裏是 「字符串列表」? – 2012-03-15 00:45:16

回答

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 

谷歌是你的朋友...

+0

好吧,我這樣做: 結果= [我[1:len(i)-1]我在l] 謝謝:) – Vanddel 2012-03-15 00:54:52

+0

不客氣! :-) – hochl 2012-03-15 10:12:24

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

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

或(相當於第一個)'進口經營者; y = map(operator.itemgetter(0),x)':-) – ephemient 2012-03-15 01:01:54