首页 > 解决方案 > Itertools 返回值未组合使用

问题描述

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基础知识,但我不知道该怎么做。感谢您的任何帮助。

标签: 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))]

推荐阅读