Python:如何将列表粘贴到另一个列表中

时间:2013-07-05 07:51:53

标签: python list

请帮我解决这个问题: 我有一个包含数字和列表的列表:

list = [1,2,[3,4,5],6,7,[8,9]]

我想得到的是一个只是数字的列表(mergin包含在父列表中的列表): 例如:

new_list = [1,2,3,4,5,6,7,8,9]

2 个答案:

答案 0 :(得分:3)

使用递归和collections.Iterable

>>> from collections import Iterable
>>> def flat(lst):
...     for parent in lst:
...         if not isinstance(parent, Iterable):
...             yield parent
...         else:
...             for child in flat(parent):
...                 yield child
...
>>> list(flat(t))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

请记住不要在他们自己的类型后命名列表:)。

答案 1 :(得分:2)

我个人使用这种方法:

这是递归flatten的功能版本,它处理元组和列表,并允许您输入任何位置参数的混合。返回一个生成整个序列的生成器,arg by arg:

flatten = lambda *n: (e for a in n
    for e in (flatten(*a) if isinstance(a, (tuple, list)) else (a,)))

用法:

l1 = ['a', ['b', ('c', 'd')]]
l2 = [0, 1, (2, 3), [[4, 5, (6, 7, (8,), [9]), 10]], (11,)]
print list(flatten(l1, -2, -1, l2))
['a', 'b', 'c', 'd', -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

这适用于python 3.x和python 2.x

以下是相同的正则表达式解决方案..

 import re

 def Flatten(TheList):
   a = str(TheList)
   b,crap = re.subn(r'[\[,\]]', ' ', a)
   c = b.split()
   d = [int(x) for x in c]

   return(d)