不带doub遍历列表

2024-04-25 14:31:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试遍历下面的代码列表,但是我对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

Tags: 代码in列表forindexlenifrange
3条回答
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]

一种方法是使用^{},它“大致相当于嵌套for循环”。你知道吗

只需将被迭代的对象作为参数,例如,您的代码变成:

import itertools

temp = [0, 2, 3, 4]

for (index, pointer), i in itertools.product(enumerate(temp), range(len(temp))):
    if i != index:
        print(temp[i])

或者既然你看起来不需要pointer

import itertools

temp = [0, 2, 3, 4]

for i, j in itertools.product(range(len(temp)), range(len(temp))):
    if i != j:
        print(temp[j])

itertools.product函数以Cartesian Product命名。你知道吗

我相信这能解决你的问题。我把这个问题想象成打印与其交叉连接的向量的元素,而不打印结果矩阵对角线上的元素。你知道吗

values = [0, 2, 3, 4]

for index in range(len(values)**2):
    if index % (len(values)+1) != 0:
        print(values[index % (len(values))])

输出:

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

相关问题 更多 >