gpt4 book ai didi

python - itertools.accumulate 但试图用 str.join 替换 lambda

转载 作者:太空狗 更新时间:2023-10-30 01:24:49 26 4
gpt4 key购买 nike

我尽量不在这里使用 lambda,因为它是循环中的性能问题,我知道 lambda 有用途,但我发现这个应该有更好的选择。

原始代码:这行得通,但我不喜欢那里的 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"]

我尝试了以下方法:

print(list(accumulate(s.split(), ' '.join)))

我一定是遗漏了一些让我觉得自己像个白痴的小东西。它必须只是打包我假设的元组的简单问题。

最佳答案

str.join 方法需要一个可迭代对象作为参数,但 accumulate 每次迭代都会向它传递两个参数,因此会出现错误。您可以改用 str.format 方法:

print(list(accumulate(s.split(), '{} {}'.format)))

关于python - itertools.accumulate 但试图用 str.join 替换 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54799197/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com