我正在根据组合做一个问题而且只是卡在里面。是的,我在python中不太好。
使用ncr的itertools组合函数只返回n中的r个可能组合。我想要一些能够返回所选r组合的东西,以及那些在该迭代中未被选中的n个其他元素。
示例:
>>>from itertools import combinations
>>>list = [1, 2, 3, 4, 5]
>>>rslt = combinations(list, 2)
选择[2, 4]
后,它还应返回[1, 3, 5]
所以它应该像[[2, 4], [1, 3, 5]]
提前致谢
答案 0 :(得分:1)
从输入迭代中返回元素的r长度子序列。
您可以使用列表推导来获取其他项目[j for j in l if j not in i]
:
from itertools import combinations
l = [1, 2, 3, 4, 5]
for i in combinations(l,2):
print(list(i),[j for j in l if j not in i])
你会得到:
[1, 2] [3, 4, 5]
[1, 3] [2, 4, 5]
[1, 4] [2, 3, 5]
[1, 5] [2, 3, 4]
[2, 3] [1, 4, 5]
[2, 4] [1, 3, 5]
[2, 5] [1, 3, 4]
[3, 4] [1, 2, 5]
[3, 5] [1, 2, 4]
[4, 5] [1, 2, 3]
顺便说一句,建议不要将list
用作变量名。
答案 1 :(得分:1)
最简单的方法是复制原始列表,删除组合中的元素:
from itertools import combinations
def combinations_and_remaining(l, n):
for c in combinations(l, n):
diff = [i for i in l if i not in c]
yield c, diff
for i in combinations_and_remaining([1, 2, 3, 4, 5], 2):
print(i)
将输出
((1, 2), [3, 4, 5])
((1, 3), [2, 4, 5])
((1, 4), [2, 3, 5])
((1, 5), [2, 3, 4])
((2, 3), [1, 4, 5])
((2, 4), [1, 3, 5])
((2, 5), [1, 3, 4])
((3, 4), [1, 2, 5])
((3, 5), [1, 2, 4])
((4, 5), [1, 2, 3])
(组合返回元组;剩余元素作为效率列表返回)
答案 2 :(得分:0)
一种稍微奢侈但有趣的方式是使用combinations
两次:
from itertools import combinations
n = 5
k = 2
lst = list(range(1, n+1))
rslt = zip(combinations(lst, k), map(tuple, reversed(list(combinations(lst, n-k)))))
print(list(rslt))
# -> [((1, 2), (3, 4, 5)), ((1, 3), (2, 4, 5)), ((1, 4), (2, 3, 5)),
# ((1, 5), (2, 3, 4)), ((2, 3), (1, 4, 5)), ((2, 4), (1, 3, 5)),
# ((2, 5), (1, 3, 4)), ((3, 4), (1, 2, 5)), ((3, 5), (1, 2, 4)),
# ((4, 5), (1, 2, 3))]
答案 3 :(得分:0)
您可以使用集合来避免循环并提高可读性:
from itertools import combinations
input = [1,2,3,4,5]
for n in itertools.combinations(input, 2):
print(n , set(n) ^ set(input))
当然,假设原始版本中没有重复版本,这会在转换为集合时丢失。