Multiple statements in list compherensions in Python?

后端 未结 9 1421
不思量自难忘°
不思量自难忘° 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: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]
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题