python - 如何简化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())
解决方案
在某些情况下,n 维数组比列表更好。
import numpy as np
x = np.array([[1, 2], [3, 4]])
print(x.reshape(-1))
print(x.reshape(-1).tolist())
推荐阅读
- javascript - Unexpected Output through \r carriage return
- c# - WebClient.UploadFile to ASP.NET MVC hosted in IIS 7 produces HTTP 415: Unsupported media type error
- html - How to set anchor tag pseudo-element width to wrap content of anchor tag?
- html - 在 CSS 中更改输入的大小
- java - 调用 GetFieldID 以在 jni 中恢复自定义 Java 类的成员 ID 时遇到奇怪的崩溃
- vue.js - Vue如何判断文件输入是否为空
- pandas - 计算列中存在的不同数量的组合
- c# - 在 asp.net core 3 中使用 SpaStaticFiles() 查看嵌入式资源
- javascript - Firebase,云功能,根据日期更改值
- powershell - 使用 PowerShell 根据名称将文件列表复制到文件夹