简体   繁体   English

Python Itertools排列

[英]Python Itertools Permutations

I am currently writing a program that uses itertools, and one piece of it does not seems to functioning properly. 我目前正在编写一个使用itertools的程序,但其中的一部分似乎无法正常运行。 I would like the input that determines the length of the lists the permutation function outputs to be equal to length of the list from which it generates its outputs. 我希望确定排列函数输出的列表长度等于其生成其输出的列表长度的输入。 In other words, I have 换句话说,我有

import itertools

b = 0
c = 9
d = [0,1,2]
e = len(d)


while b < c:
        d.append(b)
        b = b+1

print([x for x in itertools.permutations(d,e)])

And I would like this to generate all the possible permutations of d that are equal to this length. 我希望这生成等于该长度的d的所有可能排列。 I have been experimenting with this and it seems that second determiner must be an integer. 我已经对此进行了试验,似乎第二个确定因素必须是整数。 I even tried making a new variable, f, and having f = int(e) and then replacing e with f in the print statement, but with no success. 我什至尝试制作一个新变量f,并让f = int(e) ,然后在print语句中用f替换e,但没有成功。 With either of these all I got was [()] 有了这些,我得到的都是[()]

Thanks for your help. 谢谢你的帮助。

You need to set e after you build the list. 建立清单后,您需要设定e len(d) returns a value, not a reference to the list's length. len(d)返回一个值,而不是对列表长度的引用。

d = range(0,9)  # build an arbitrary list here
                # this creates a list of numbers: [0,1,2,3,4,5,6,7,8]
e = len(d)
print list(itertools.permutations(d, e))

Note that the number of permutations is very large, so storing all of them in a list will consume large amounts of memory - you'd be better off with this: 请注意,排列的数量非常多,因此将所有排列存储在列表中将消耗大量内存-您最好这样做:

d = range(0,9)
e = len(d)
for p in itertools.permutations(d, e):
    print p

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

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