如何将 itertools.permutations(“0123456789”) 的结果(在 python 中)转换为字符串列表
在Python中,我使用list(itertools.permutations("0123456789")),并且我收到(如预期的那样)单个字符串的元组列表。
有没有办法将该结果转换为字符串列表,而无需迭代所有 3628800 个项目?
In Python, I am using list(itertools.permutations("0123456789"))
, and I am receiving (I as expected) a list of tuples of singled character strings.
Is there a way to turn that result into a list of strings, without iterating over all 3628800 items?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想在不迭代整个列表的情况下执行此操作,而是根据需要懒惰地执行此操作,则可以使用itertools.imap:(
请注意,我没有使用< code>list() 在
permutations
的结果上,所以它尽可能地懒)或者,正如评论中指出的,一个简单的生成器表达式也可以在这里工作:
itertools.imap
还有一个额外的好处,即能够使用方便的语法对大量可迭代对象应用相同的函数(只需将它们添加为后续参数),但这对于这种特定用法来说并不是必需的,因为我们只有一个可迭代的If you want to do it without iterating over the whole list but rather lazily doing it as needed, you can use
itertools.imap
:(note that I'm not using
list()
on the result ofpermutations
here so it's as lazy as possible)Or, as pointed out in the comments, a simple generator expression would work here as well:
itertools.imap
has the additional benefit of being able to apply the same function on lots of iterables with a convenient syntax (simply adding them as subsequent arguments), but that's not necessary for this particular usage as we only have one iterable将其转换为列表会迭代整个事情。您可以将其转换为具有列表理解的列表,这比将其转换为列表然后迭代列表中的所有项目更好:
如果您不需要以列表结尾,则生成器表达式就足够了(将
[]
替换为()
)。Turning it into a list iterates over the whole thing. You can turn it into a list with a list comprehension, which will be better than turning it into a list then iterating over all the items of the list:
If you don't need to end up with a list, a generator expression will suffice (replace
[]
with()
).