简体   繁体   English

Python:创建N的组合,其中2个项目为常数

[英]Python: create combinations of N where 2 of the items are constant

Using itertools.combinations, the following works great: 使用itertools.combinations,可以很好地完成以下工作:

for letter_group in itertools.combinations(alphabet, 5):
    print letter group

Now I want to have the first 2 of the 5 items in the combinations constant. 现在,我要使组合中的5个项目中的前2个保持不变。 Is there a way to do that? 有没有办法做到这一点?

For example, the output would then be: 例如,输出将是:

(a,b,c,d,e)
(a,b,e,f,g)
...
(a,b,x,y,z)

Well, I think what you're trying to do is make 5-tuples where the first 2 are specified and the last 3 are from an iterable called alphabet , but where the last 3 can't reuse the first two. 好吧,我想您想做的是使5元组,其中指定了前2个,后3个来自可迭代的称为alphabet ,但后3个不能重用前两个。

How about this: 这个怎么样:

start = ('a', 'b')
for ending in itertools.combinations(set(alphabet) - set(start), 3):
    print start + ending

Just make your alphabet without the first two letters, do combinations of the rest, then contact ['a', 'b'] with the result, the runnable code: 只需使您的alphabet不包含前两个字母,然后对其余的字母进行组合,然后与['a','b']取得联系,并生成可运行的代码:

# -*- coding: utf-8 -*-
import string
import itertools

alphabet = string.letters[:26]
prefix = ['a', 'b']

for letter_group in itertools.combinations(alphabet[len(prefix):], 3):
    print prefix + list(letter_group)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM