Python3 中的双循环

Double for loop in Python3

有一个名为 L 的列表。 其中包含其他列表:L=[A,B,C,...N] 我想 for-loop,其中 B 不等于 A(参见 #2) 类似于:因为 B 不是 L 中的 A:

for A in L: #1
    for B in L: #2

我该怎么做?

只需按索引访问列表的其余部分:

for i in xrange(len(L)-1):
    for j in xrange(i+1, len(L)):
        #L[i] != L[j] always, and will check just one list against the others once

使用 itertools 的更好解决方案,或者 with permutations or with combinations:

import itertools

# If it's okay to see L[1], L[2], and later L[2], L[1], that is, order sensitive,
# matching your original question's specification of only avoiding pairing with self:
for A, B in itertools.permutations(L, 2):
    ...

# If you only want to see L[x] paired with L[y] where y > x,
# equivalent to results of Daniel Sanchez's answer:
for A, B in itertools.combinations(L, 2):
    ...

其中任何一个都比使用需要索引的嵌套循环快得多(还有好处,只需要一级缩进,减少代码中的 "arrow patterns")。

如果循环体是 print(A, B, sep=',', end=' ')L = [1, 2, 3]permutations 循环的输出将是:

1,2 1,3 2,1 2,3 3,1 3,2

对于 combinations,您将获得:

1,2 1,3 2,3

所以请选择与您想要的行为相匹配的那个。

使用 itertools 函数的另一个好处是,当 L 是一个非序列集合(例如 set)或当它是一个只能遍历一次的迭代器(它们会在内部缓存这些值,以便它们可以多次生成它们)。其他解决方案需要显式转换为 list/tuple 等以处理“L 是一次性迭代器”的情况。

您可以使用 if 语句过滤掉不需要的情况:

for A in L:
    for B in L:
        if A == B:
            continue # skip
        # do stuff ...