首页 > 解决方案 > 如何简化python中的两个嵌套循环

问题描述

我试图在 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())

标签: pythonarrayslistloopsfor-loop

解决方案


在某些情况下,n 维数组比列表更好。

import numpy as np
x = np.array([[1, 2], [3, 4]]) 
print(x.reshape(-1))
print(x.reshape(-1).tolist())

推荐阅读