[英]Python combinations of list elements with condition
I find source code of itertools.combinations()
function in python.我在 python 中找到
itertools.combinations()
函数的源代码。 It looks like this.它看起来像这样。
def combinations(iterable, r):
pool = tuple(iterable)
n = len(pool)
if r > n:
return
indices = list(range(r))
print(indices)
yield tuple(pool[i] for i in indices)
while True:
for i in reversed(range(r)):
if indices[i] != i + n - r:
break
else:
return
indices[i] += 1
for j in range(i+1, r):
indices[j] = indices[j-1] + 1
print(indices)
yield tuple(pool[i] for i in indices)
I have tuples like this:我有这样的元组:
pairs = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
I need to generate foursomes of all possible combinations, but with condition, that there will be always only two same numbers in list.我需要生成所有可能组合的四人组,但有条件,列表中总是只有两个相同的数字。 So in this case this 3 list I want to generate:
所以在这种情况下,我想生成这 3 个列表:
((0, 1), (0, 2), (1, 3), (2, 3))
((0, 1), (0, 3), (1, 2), (2, 3))
((0, 2), (0, 3), (1, 2), (1, 3))
What I realy need is to update code of generation combinations, because in my real app I need to generate 23-nties from 80 tuples.我真正需要的是更新生成组合的代码,因为在我真正的应用程序中,我需要从 80 个元组生成 23-nties。 Generation and filtering after it would take a lot of time, thats why I need to catch problem in part of generation.
生成和过滤之后会花费很多时间,这就是为什么我需要在部分生成中捕获问题。
You can use itertools.combinations
and then filter the result using collections.Counter
:您可以使用
itertools.combinations
然后使用collections.Counter
过滤结果:
from collections import Counter
import itertools as it
pairs = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
result = filter(
lambda x: max(Counter(it.chain(*x)).values()) < 3,
it.combinations(pairs, 4)
)
print(list(result))
Output:输出:
[((0, 1), (0, 2), (1, 3), (2, 3)),
((0, 1), (0, 3), (1, 2), (2, 3)),
((0, 2), (0, 3), (1, 2), (1, 3))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.