Multiple statements in list compherensions in Python?

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

    For your edited example:

    currentValue += sum(list1)
    

    or:

    for x in list1:
        currentValue += x
    

    List comprehensions are great, I love them, but there's nothing wrong with the humble for loop and you shouldn't be afraid to use it :-)

    EDIT: "But what if I wanna increment different than the collected values?"

    Well, what do you want to increment by? You have the entire power of python at your command!

    Increment by x-squared?

    for x in list1:
        currentValue += x**2
    

    Increment by some function of x and its position in the list?

    for i, x in enumerate(list1):
        currentValue += i*x
    

提交回复
热议问题