簡體   English   中英

Itertools 返回值未組合使用

[英]Itertools return value NOT used in combinations

for num in combinations(nums[0], number):使用for num in combinations(nums[0], number):返回列表中數字的所有組合,其中num = len(nums[0])-1

我想要做的是返回,作為一個單獨的變量,未在每個組合中使用的列表項的值,例如,如果nums[1,2,3]那么我希望它返回:

[1,2],[3]   
[1,3],[2]  
[2,3],[1]  

如果這不清楚,請告訴我。 我覺得這可能是一些基本的 Python 基礎知識,但我不知道該怎么做。 感謝您的任何幫助。

由於您的列表可能有重復項:

from itertools import combinations

nums = [1, 2, 3, 3]

# get combinations of all possible lengths
combos = []
for n in range(len(nums)):
    combos += combinations(nums, n)

# create the pairs you want, but with all nums
combo_pairs = [(combo, list(nums)) for combo in combos]
# remove the nums that are in the combination for each pair
for combo, combo_nums in combo_pairs:
    for n in combo:
        combo_nums.remove(n)

print(combo_pairs)

注意:這將導致重復值的重復(一個用於三個,一個用於另一個)。 你可以擺脫這樣的人:

combo_pairs = list(set([(combo, tuple(combo_nums)) for combo, combo_nums in combo_pairs]))

這會將一對中的 nums 變成一個元組,因為元組是可散列的,但列表不是。 當然,如果您需要,您可以隨時轉換回列表。

如果您只對長度比原始長度少 1 的組合感興趣,您可以這樣做:

from itertools import combinations

nums = [1, 2, 3, 3]

# get combinations of correct length
combos = combinations(nums, len(nums)-1)

# create the pairs you want, but with all nums
combo_pairs = [(combo, list(nums)) for combo in combos]
# remove the nums that are in the combination for each pair
for combo, combo_nums in combo_pairs:
    for n in combo:
        combo_nums.remove(n)

print(combo_pairs)

但在這種情況下,你也可以:

nums = [1, 2, 3, 3]
combos = [(nums[:n] + nums[n+1:], [nums[n]]) for n in range(len(nums))]

由於組合的其余部分由“遺漏”的元素唯一確定,因此您實際上並不需要 itertools。

def combinations_leaving_one_out(lst):
    lst = sorted(lst)
    prev_x = None
    for i, x in enumerate(lst):
        if x != prev_x:
            yield tuple(lst[:i] + lst[i+1:]), x
        prev_x = x

例子:

>>> lst = [1, 2, 3, 1, 2, 4]
>>> for comb, left_out in combinations_leaving_one_out(lst):
...     print(comb, left_out)
... 
(1, 2, 2, 3, 4) 1
(1, 1, 2, 3, 4) 2
(1, 1, 2, 2, 4) 3
(1, 1, 2, 2, 3) 4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM