Multiple statements in list compherensions in Python?

后端 未结 9 1658
不思量自难忘°
不思量自难忘° 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条回答
  •  萌比男神i
    2021-02-13 08:05

    I'm not quite sure what you're trying to do but it's probably something like

    list2 = [(i, i*2, i) for i in list1]
    print list2
    

    The statement in the list comprehension has to be a single statement, but you could always make it a function call:

    def foo(i):
        print i
        print i * 2
        return i
    list2 = [foo(i) for i in list1]
    

提交回复
热议问题