【发布时间】:2019-12-19 11:18:13
【问题描述】:
我正在尝试在 python 中简化两个需要的 for 循环,但我无法解决这个问题。 我的代码:
head = [[1, 2], [3, 4]]
temp = []
for array in head:
for element in array:
temp.append(element)
print(temp)
========OUTPUT========
[1, 2, 3, 4]
我试试:
head = [[1, 2], [3, 4]]
temp = []
for array in head:
temp += [element for element in array]
print(temp)
但只能简化一个循环
编辑:解决方案
@serafeim 针对我的案例的具体解决方案:
head = [[1, 2], [3, 4]]
print([element for array in head for element in array])
其他解决方案:
匿名
from functools import reduce
head = [[1, 2], [3, 4]]
print(reduce(list.__add__, head))
作者:@chepner
from itertools import chain
head = [[1, 2], [3, 4]]
print([x for x in chain.from_iterable(head)])
作者:@R-zu
import numpy as np
head = [[1, 2], [3, 4]]
print(np.array(head).reshape(-1).tolist())
【问题讨论】:
-
好问题。在这里查看我的帖子:stackoverflow.com/a/57468777/5025009
-
@Prune 这不是完全重复的。我建议删除它并让 OP 保持打开状态
-
哦,谢谢!解决了我的问题
-
@Prune 尽快重新打开 OP
-
我在论坛中找到了一种新方法。从标准库
functools导入reduce可以做到temp = reduce(list.__add__, head)
标签: python arrays list loops for-loop