Multiple statements in list compherensions in Python?

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

    As pjz said, you can use functions, so here you can use a closure to keep track of the counter value:

    # defines a closure to enclose the sum variable
    def make_counter(init_value=0):
        sum = [init_value]
        def inc(x=0):
            sum[0] += x
            return sum[0]
        return inc
    

    Then you do what you want with list1:

    list1 = range(5)  # list1 = [0, 1, 2, 3, 4]
    

    And now with just two lines, we get list2:

    counter = make_counter(10)  # counter with initial value of 10
    list2 = reduce(operator.add, ([counter(x), x] for x in list1))
    

    In the end, list2 contains:

    [10, 0, 11, 1, 13, 2, 16, 3, 20, 4]
    

    which is what you wanted, and you can get the value of the counter after the loop with one call:

    counter()  # value is 20
    

    Finally, you can replace the closure stuff by any kind of operation you want, here we have an increment, but it's really up to you. Note also that we use a reduce to flatten list2, and this little trick requires you to import operator before calling the line with the reduce:

    import operator
    

提交回复
热议问题