Skip to main content
 首页 » 编程设计

python之迭代同一个列表两次并避免在 python 中重复

2025年05月04日15lori

我有一个列表 [1,2,3,4,5] 我用 for 循环迭代了两次。

for i in list: 
    for j in list: 
        print(i,j) 

我不关心 i 和 j 的顺序,因此我收到了很多重复项。例如 1,2 和 2,1 对我来说是“相同的”。 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 

另外如评论中所述,您可以使用 itertools.combinations_with_replacement如果你想要像 (n, n) 这样的元组:

>>> 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)]