[英]Python Itertools.Permutations()
为什么itertools.permutations()返回每个排列的字符或数字列表,而不是只返回一个字符串?
例如:
>>> print([x for x in itertools.permutations('1234')])
>>> [('1', '2', '3', '4'), ('1', '2', '4', '3'), ('1', '3', '2', '4') ... ]
为什么不归还呢?
>>> ['1234', '1243', '1324' ... ]
itertools.permutations()
只是这样工作。 它需要一个任意的iterable作为参数,并且总是返回一个产生元组的迭代器。 它不(也不应该)特殊情况字符串。 要获取字符串列表,您可以自己加入元组:
list(map("".join, itertools.permutations('1234')))
因为它期望迭代作为参数而不知道,所以它是一个字符串。 该参数在文档中描述。
http://docs.python.org/library/itertools.html#itertools.permutations
我没试过,但很可能应该工作
comb = itertools.permutations("1234",4)
for x in comb:
''.join(x)
可以为字符串和列表进行查询,下面是示例..
x = [1,2,3]
如果你需要做排列上面的列表
print(list(itertools.permutations(x, 2)))
# the above code will give the below..
# [(1,2),(1,3),(2,1)(2,3),(3,1),(3,2)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.