为什么 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' ... ]
Why does itertools.permutations() return a list of characters or digits for each permutation, instead of just returning a string?
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' ... ]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
itertools.permutations() 就是这样工作的。它接受任意可迭代对象作为参数,并始终返回一个生成元组的迭代器。它没有(也不应该)特殊情况的字符串。要获取字符串列表,您始终可以自己连接元组:
itertools.permutations()
simply works this way. It takes an arbitrary iterable as an argument, and always returns an iterator yielding tuples. It doesn't (and shouldn't) special-case strings. To get a list of strings, you can always join the tuples yourself:因为它需要一个可迭代对象作为参数,但不知道它是一个字符串。该参数在文档中进行了描述。
http://docs.python.org/library/itertools.html#itertools.permutations
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
也可以对字符串和列表进行排列,下面是示例..
如果您需要对上面的列表进行排列
Perumatation can be done for strings and list also, below is the example..
if you need to do permutation the above list
我没有尝试过,但很可能应该有效
I have not tried, but most likely should work