Python itertools组合

时间:2013-10-23 02:16:26

标签: python tuples combinations

这个简单的脚本适用于4个元素,但如果我想更改元素的数量,它会找到它的组合不起作用。

我的意思是它只能在4中找到组合,我希望能够指定它能找到多少个组合。

data = (("Jackson",10,12,"A"),
     ("Ryan",10,20,"A"),
     ("Michael",10,12,"B"),
     ("Andrew",10,20,"B"),
     ("McKensie",10,12,"C"),
     ("Alex",10,20,"D"))
numberOfElements = 4
import itertools
for combo in itertools.combinations(data, numberOfElements):
    if len({item[3] for item in combo}) == numberOfElements:
        print combo

上面的输出表格

(('Jackson', 10, 12, 'A'), ('Michael', 10, 12, 'B'), ('McKensie', 10, 12, 'C'), ('Alex', 10, 20, 'D')) (('Jackson', 10, 12, 'A'), ('Andrew', 10, 20, 'B'), ('McKensie', 10, 12, 'C'), ('Alex', 10, 20, 'D')) (('Ryan', 10, 20, 'A'), ('Michael', 10, 12, 'B'), ('McKensie', 10, 12, 'C'), ('Alex', 10, 20, 'D')) (('Ryan', 10, 20, 'A'), ('Andrew', 10, 20, 'B'), ('McKensie', 10, 12, 'C'), ('Alex', 10, 20, 'D'))

缺少大于4的所有组合。如果我更改元素数量,则没有输出。我的问题是,当我改变元素的数量时,我想知道为什么我没有输出。

3 个答案:

答案 0 :(得分:1)

原因是这一行:

if len({item[3] for item in combo}) == numberOfElements:

编辑 - 我不太明白这条线在做什么。

元素3(A,B,C,D)只有4个选项,因此对于大于4的numberOfElements值,此行永远不会评估为真。

答案 1 :(得分:0)

关键是您的数据集在第3列中只有值A,B,C和D;它不可能在一组中有超过4个。

编辑:刚编辑了我的答案后想到了希望登录的答案指出了相同的内容。

答案 2 :(得分:-3)

一次4个组合:

>>> import itertools as it
>>> data = 'abcdef'
>>> r = 4
>>> for thing in it.combinations(data, r):
    print ''.join(thing),

abcd abce abcf abde abdf abef acde acdf acef adef bcde bcdf bcef bdef cdef

一次采取2,3,4,5和6的组合:

>>> for r in xrange(2,len(data) + 1):
    for thing in it.combinations(data, r):
        print ''.join(thing)


ab
ac
ad
ae
af
bc
bd
be
bf
cd
ce
cf
de
df
ef
abc
abd
abe
abf
acd
ace
acf
ade
adf
aef
bcd
bce
bcf
bde
bdf
bef
cde
cdf
cef
def
abcd
abce
abcf
abde
abdf
abef
acde
acdf
acef
adef
bcde
bcdf
bcef
bdef
cdef
abcde
abcdf
abcef
abdef
acdef
bcdef
abcdef
>>>