首页 > 解决方案 > 遍历一个没有 double for 的列表

问题描述

我正在尝试像下面的代码一样遍历一个列表,但我在 python 中有点新,我想知道是否有机会克服这两个 for 循环。有什么办法吗?提前致谢

temp = [0, 2, 3, 4]
for index, pointer in enumerate(temp):
    for i in range(len(temp)):
        if i != index:
           print(temp[i])

结果 :

2
3
4
0
3
4
0
2
4
0
2
3

标签: pythonlistdata-structures

解决方案


temp = [0, 2, 3, 4]
sol=[]
for i in range(len(temp)):
    sol.extend(temp[:i]+temp[i+1:])
print(sol)

输出

 [2, 3, 4, 0, 3, 4, 0, 2, 4, 0, 2, 3]

推荐阅读