簡體   English   中英

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

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

我想找到我的數字列表的所有組合,而不是相同的組合。 我在下面寫的代碼給了我所有的組合。 所以,我也得到了 [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]:

試試這個代碼

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