Multiple statements in list compherensions in Python?

后端 未结 9 1464
不思量自难忘°
不思量自难忘° 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:09

    You can't do multiple statements, but you can do a function call. To do what you seem to want above, you could do:

    list1 = ...
    list2 = [ (sum(list1[:i], i) for i in list1 ]
    

    in general, since list comprehensions are part of the 'functional' part of python, you're restricted to... functions. Other folks have suggested that you could write your own functions if necessary, and that's also a valid suggestion.

提交回复
热议问题