遍历同一个列表两次并避免 python 中的重复项
Iterate over same list twice and avoid duplicates in python
我有一个列表 [1,2,3,4,5]
,我用 for 循环对其进行了两次迭代。
for i in list:
for j in list:
print(i,j)
我不关心 i 和 j 的顺序,因此我收到了很多重复的。例如 1,2 和 2,1 对我来说是 "same"。 1,4 和 4,1 以及 3,5 和 5,3 等也是如此。
我想删除这些重复项,但不太明白我应该怎么做。
实际上你想要组合:
>>> list(combinations( [1,2,3,4,5],2))
[(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]
因为 itertools.combinations
的结果是一个生成器,如果你想遍历它,你不需要 list
:
for i,j in combinations( [1,2,3,4,5],2):
#do stuff
另外如评论中所述,如果您想要像 (n, n) 这样的元组,您可以使用 itertools.combinations_with_replacement
:
>>> list(combinations_with_replacement([1, 2, 3, 4, 5],2))
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 3), (3, 4), (3, 5), (4, 4), (4, 5), (5, 5)]
我有一个列表 [1,2,3,4,5]
,我用 for 循环对其进行了两次迭代。
for i in list:
for j in list:
print(i,j)
我不关心 i 和 j 的顺序,因此我收到了很多重复的。例如 1,2 和 2,1 对我来说是 "same"。 1,4 和 4,1 以及 3,5 和 5,3 等也是如此。
我想删除这些重复项,但不太明白我应该怎么做。
实际上你想要组合:
>>> list(combinations( [1,2,3,4,5],2))
[(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]
因为 itertools.combinations
的结果是一个生成器,如果你想遍历它,你不需要 list
:
for i,j in combinations( [1,2,3,4,5],2):
#do stuff
另外如评论中所述,如果您想要像 (n, n) 这样的元组,您可以使用 itertools.combinations_with_replacement
:
>>> list(combinations_with_replacement([1, 2, 3, 4, 5],2))
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 3), (3, 4), (3, 5), (4, 4), (4, 5), (5, 5)]