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.
Original code: this works but I don't like that lambda there.
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. You can use the str.format
method instead:
print(list(accumulate(s.split(), '{} {}'.format)))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.