[英]itertools.accumulate but trying to replace lambda with str.join
I'm trying not to use lambda here because of it's performance issues in loops, I know there's uses for lambda but I find this one should have a better alternative. 我试图不在这里使用lambda,因为它在循环中的性能问题,我知道有用于lambda但我发现这个应该有更好的选择。
Original code: this works but I don't like that lambda there. 原始代码: 这有效,但我不喜欢那里的lambda。
from itertools import accumulate
s = "lorem ipsum dolor"
print(list(accumulate(s.split(), lambda x, y: f'{x} {y}')))
#["lorem", "lorem ipsum", "lorem ipsum dolor"]
I have tried the following: 我尝试过以下方法:
print(list(accumulate(s.split(), ' '.join)))
I must be missing something small here that will make me feel like an idiot. 我必须在这里遗漏一些小东西,这会让我觉得自己像个白痴。 It has to be just a simple matter of packing the tuple I assume. 它必须只是包装我假设的元组的简单问题。
The str.join
method expects an iterable as an argument, and yet accumulate
passes to it two arguments for each iteration, hence the error. str.join
方法期望一个iterable作为参数,然后accumulate
为每次迭代传递两个参数,因此错误。 You can use the str.format
method instead: 您可以使用str.format
方法:
print(list(accumulate(s.split(), '{} {}'.format)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.