简体   繁体   English

Python Itertools.Permutations()

[英]Python Itertools.Permutations()

Why does itertools.permutations() return a list of characters or digits for each permutation, instead of just returning a string? 为什么itertools.permutations()返回每个排列的字符或数字列表,而不是只返回一个字符串?

For example: 例如:

>>> print([x for x in itertools.permutations('1234')])
>>> [('1', '2', '3', '4'), ('1', '2', '4', '3'), ('1', '3', '2', '4') ... ]

Why doesn't it return this? 为什么不归还呢?

>>> ['1234', '1243', '1324' ... ]

itertools.permutations() simply works this way. itertools.permutations()只是这样工作。 It takes an arbitrary iterable as an argument, and always returns an iterator yielding tuples. 它需要一个任意的iterable作为参数,并且总是返回一个产生元组的迭代器。 It doesn't (and shouldn't) special-case strings. 它不(也不应该)特殊情况字符串。 To get a list of strings, you can always join the tuples yourself: 要获取字符串列表,您可以自己加入元组:

list(map("".join, itertools.permutations('1234')))

Because it expects an iterable as a parameter and doesn't know, it's a string. 因为它期望迭代作为参数而不知道,所以它是一个字符串。 The parameter is described in the docs. 该参数在文档中描述。

http://docs.python.org/library/itertools.html#itertools.permutations http://docs.python.org/library/itertools.html#itertools.permutations

I have not tried, but most likely should work 我没试过,但很可能应该工作

comb = itertools.permutations("1234",4)
for x in comb: 
  ''.join(x)    

Perumatation can be done for strings and list also, below is the example.. 可以为字符串和列表进行查询,下面是示例..

x = [1,2,3]

if you need to do permutation the above list 如果你需要做排列上面的列表

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.

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