gpt4 book ai didi

python - Itertools 返回值不用于组合

转载 作者:行者123 更新时间:2023-12-01 00:04:31 26 4
gpt4 key购买 nike

我使用 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]))

这会将对中的数字转换为元组,因为元组是可散列的,但列表不是。当然,如果需要的话,您可以随时转换回列表。

如果您只对长度比原始长度小 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))]

关于python - Itertools 返回值不用于组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60068015/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com