对于我能想到的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()
在什么情况下会是最合适的解决方案?如果有的话,是在什么情况下使用?
tuple(itertools.repeat('example', 5))
),第二个将'example'
本身乘以五次以创建'exampleexampleexampleexampleexample'
,因为('example')
本身并没有创建一个元组(你需要使用('example',) * 5
),而你的第三个示例使用了map
,这会返回一个map
对象,因为 Python 3 中的map
是惰性的(你需要将其包装在list
中才能得到提供的结果)。这是一个有趣的问题,但是伪造你的代码示例会损害它的可信度。 - ShadowRanger