迭代相同的列表两次,避免在python中重复

ric*_*kri 1 python list duplicates

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

for i in list:
    for j in list:
        print(i,j)
Run Code Online (Sandbox Code Playgroud)

我不关心i和j的顺序,因此我收到了很多重复.例如1,2和2,1对我来说是"相同的".对于1,4和4,1以及3,5和5,3等同样的事情.

我想删除这些副本,但不明白我应该怎么做.

Kas*_*mvd 7

其实你想要的组合:

>>> 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)]
Run Code Online (Sandbox Code Playgroud)

itertools.combinations如果你想循环它是一个生成器的结果,你不需要list:

for i,j in combinations( [1,2,3,4,5],2):
      #do stuff
Run Code Online (Sandbox Code Playgroud)

另外如评论中所述,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)]
Run Code Online (Sandbox Code Playgroud)