简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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