Python 扩展列表中任意数量的子列表
我试图在列表中展开子列表。我为列表中的一层子列表编写了它。有没有更好的方法来编写此代码,以便为任意数量的嵌套列表进行缩放?见以下示例:Python 扩展列表中任意数量的子列表,python,Python,我试图在列表中展开子列表。我为列表中的一层子列表编写了它。有没有更好的方法来编写此代码,以便为任意数量的嵌套列表进行缩放?见以下示例: a = [1, 2, 3] b = [4, 5, 6] c = [a, b] def expand(x): # expands a list of lists with no further sublists a = [] for i in x: # could also here do a += i and avoi
a = [1, 2, 3]
b = [4, 5, 6]
c = [a, b]
def expand(x):
# expands a list of lists with no further sublists
a = []
for i in x:
# could also here do a += i and avoid the second for loop
for j in i:
a.append(j)
return a
print expand(c)
返回所需的[1,2,3,4,5,6]
为了进一步澄清,我想知道如何更好地扩展
`e=[c,a,b]'和进一步的嵌套迭代
c = [[1, 2, 3], [4, 5, 6]]
# first method
res = [x for lst in c for x in lst]
# second method
from itertools import chain
res = list(chain(*c))
编辑:他想要迭代嵌套列表
编辑:他想要迭代嵌套列表
使用递归:
def flat_list(l):
for a in l:
if isinstance(a, list):
for x in flat_list(a):
yield x
else:
yield a
a = [1, 2, 3]
b = [4, 5, 6]
c = [a, b]
e = [c, a, b]
print list(flat_list(c))
print list(flat_list(e))
输出为:
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
使用递归:
def flat_list(l):
for a in l:
if isinstance(a, list):
for x in flat_list(a):
yield x
else:
yield a
a = [1, 2, 3]
b = [4, 5, 6]
c = [a, b]
e = [c, a, b]
print list(flat_list(c))
print list(flat_list(e))
输出为:
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
一个解决方案:
def flatten(ls):
result = []
stack = [ls]
while stack:
if isinstance(stack[-1], list):
try: stack.append(stack[-1].pop(0))
except IndexError: stack.pop() # remove now-empty sublist
else:
result.append(stack.pop())
return result
a = [1, 2, 3]
b = [4, 5, 6]
c = [a, b]
e = [c, a, b]
print flatten(e)
输出:
[1, 2, 3, 4, 5, 6]
或:
使用总和:
>>> e
[[[1, 2, 3], [4, 5, 6]], [1, 2, 3], [4, 5, 6]]
>>> sum(e[0], [])
[1, 2, 3, 4, 5, 6]
使用reduce:
>>> reduce(lambda x,y: x+y, e[0])
[1, 2, 3, 4, 5, 6]
>>>
一个解决方案:
def flatten(ls):
result = []
stack = [ls]
while stack:
if isinstance(stack[-1], list):
try: stack.append(stack[-1].pop(0))
except IndexError: stack.pop() # remove now-empty sublist
else:
result.append(stack.pop())
return result
a = [1, 2, 3]
b = [4, 5, 6]
c = [a, b]
e = [c, a, b]
print flatten(e)
输出:
[1, 2, 3, 4, 5, 6]
或:
使用总和:
>>> e
[[[1, 2, 3], [4, 5, 6]], [1, 2, 3], [4, 5, 6]]
>>> sum(e[0], [])
[1, 2, 3, 4, 5, 6]
使用reduce:
>>> reduce(lambda x,y: x+y, e[0])
[1, 2, 3, 4, 5, 6]
>>>
+1对于itertools方法。我相信itertools和collections是python的stdlib.+1的itertools方法中功能最强大但使用不足的两个模块。我相信itertools和collections是python的stdlib中功能最强大但使用不足的两个模块。