Multiple statements in list compherensions in Python?

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

    First of all, you likely don't want to use print. It doesn't return anything, so use a conventional for loop if you just want to print out stuff. What you are looking for is:

    >>> list1 = (1,2,3,4)
    >>> list2 = [(i, i*2) for i in list1] # Notice the braces around both items
    >>> print(list2)
    [(1, 2), (2, 4), (3, 6), (4, 8)]
    

提交回复
热议问题