Multiple statements in list compherensions in Python?

后端 未结 9 1412
不思量自难忘°
不思量自难忘° 2021-02-13 07:09

Is it possible to have something like:

list1 = ...

currentValue = 0
list2 = [currentValue += i, i for i in list1]

I tried that but didn\'t wor

9条回答
  •  梦谈多话
    2021-02-13 08:01

    Statements cannot go inside of expressions in Python; it was a complication that was deliberately designed out of the language. For this problem, try using a complication that did make it into the language: generators. Watch:

    def total_and_item(sequence):
        total = 0
        for i in sequence:
            total += i
            yield (total, i)
    
    list2 = list(total_and_item(list1))
    

    The generator keeps a running tally of the items seen so far, and prefixes it to each item, just like it looks like you example tries to do. Of course, a straightforward loop might be even simpler, that creates an empty list at the top and just calls append() a lot! :-)

提交回复
热议问题