【发布时间】:2012-02-21 23:16:30
【问题描述】:
对于我能想到的 Python 的 itertools.repeat() 类的每一次使用,我都能想到另一个同样(可能更多)可接受的解决方案来达到同样的效果。例如:
>>> [i for i in itertools.repeat('example', 5)]
['example', 'example', 'example', 'example', 'example']
>>> ['example'] * 5
['example', 'example', 'example', 'example', 'example']
>>> list(map(str.upper, itertools.repeat('example', 5)))
['EXAMPLE', 'EXAMPLE', 'EXAMPLE', 'EXAMPLE', 'EXAMPLE']
>>> ['example'.upper()] * 5
['EXAMPLE', 'EXAMPLE', 'EXAMPLE', 'EXAMPLE', 'EXAMPLE']
在任何情况下itertools.repeat() 是最合适的解决方案吗?如果有,在什么情况下?
【问题讨论】:
-
我添加了一个新答案,显示了 itertools 重复的原始激励用例。此外,我刚刚更新了 Python 文档以反映此使用说明。
-
您的 4 个代码示例中有 3 个实际上不起作用。第一个创建生成器表达式,而不是
tuple(你想要tuple(itertools.repeat('example', 5))),第二个将'example'本身相乘以生成'exampleexampleexampleexampleexample',因为('example')在第一个中不会生成tuple放置(您需要('example',) * 5),而您的第三个示例使用map,它将返回一个map对象,因为Python 3map是惰性的(您必须将其包装在list中才能获得提供的结果)。这是一个有趣的问题,但伪造你的代码示例会伤害它。 -
@ShadowRanger,当我发表这篇文章时,我对 Python 还很陌生,我只是快速输入了一些示例,而没有检查实际输出。有点迂腐,但我现在已经修好了。谢谢! :)
标签: python python-3.x itertools