python - 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基础知识,但我不知道该怎么做。感谢您的任何帮助。
解决方案
由于您的列表可能有重复项:
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))]
推荐阅读
- c# - 亚马逊 MWS ListOrderItems 节流问题
- html - 一些具有相同id的选择,它是正确的还是错误的
- javascript - 无法在快速反应组件中发送 JSON
- android - 某类的意思
- xcode - Xcode 10、sourcery 和 swiftlint 构建阶段顺序
- php - 如何修复 Laravel 5.7 中的“类签名不存在”错误?
- c# - 按钮单击无法使 H1 可见 (asp.net)
- java - 原因:org.usb4java.LoaderException:在类路径/org/usb4java/windows-x86_64/libusb-1.0.dll 中找不到本机库
- python - 如何用super构造类实例?
- arrays - Ruby,在一行中打印所有哈希“子字段”