Python Itertools.Permutations() [英] Python Itertools.Permutations()

查看:42
本文介绍了Python Itertools.Permutations()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 itertools.permutations() 为每个排列返回一个字符或数字列表,而不是只返回一个字符串?

例如:

<预><代码>>>>打印([x for x in itertools.permutations('1234')])>>>[('1', '2', '3', '4'), ('1', '2', '4', '3'), ('1', '3', '2','4') ... ]

为什么不返回这个?

<预><代码>>>>['1234', '1243', '1324' ... ]

解决方案

itertools.permutations() 就是这样工作的.它接受一个任意的可迭代对象作为参数,并且总是返回一个迭代器产生元组.它不会(也不应该)特殊情况的字符串.要获取字符串列表,您始终可以自己加入元组:

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

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' ... ]

解决方案

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:

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

这篇关于Python Itertools.Permutations()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆