简体   繁体   English

在python中查找数字列表的所有组合而不是相同的组合

[英]Finding all combinations of a list of numbers without the pair being the same in python

I would like to find all combinations of my list of numbers without the pair being the same.我想找到我的数字列表的所有组合,而不是相同的组合。 The code I've written below gives me all combinations.我在下面写的代码给了我所有的组合。 So, I also get [1, 1], [2, 2] and [3, 3], which I'd like to remove.所以,我也得到了 [1, 1]、[2, 2] 和 [3, 3],我想删除它们。

nr_list = [1, 2, 3]
combinations = []
for a in nr_list:
    for b in nr_list:
        pair = [a, b]
        combinations.append(pair)
print(combinations)
from itertools import permutations
nr_list = [1, 2, 3]
print(list(permutations(nr_list,2)))
# [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

如果pair中的项相等,即if pair[0] != pair[1]:则不要将pair添加到组合中if pair[0] != pair[1]:

Try this code试试这个代码

nr_list = [1, 2, 3]
combinations = []
for a in nr_list:
    for b in nr_list:
        if(a!=b):
            pair = [a, b]
            combinations.append(pair)
print(combinations)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM