use for loop with if/elif statement in python list

2019-07-17 09:10发布

问题:

This question already has an answer here:

  • Multiple If/else in list comprehension python 4 answers

I am trying to translate this for loop into a list comprehension:

a = [1,2,3,4,5,6,7,8,9]
result = []
for i in a:
    if i <= 3:
        result.append(1)
    elif i > 4 and i < 7:
        result.append(2)

and I have tried this

[1 if i <= 3 else 2 if i > 3 and i < 7 for i in a]

which complains about

File "<ipython-input-155-eebf07a9e0d8>", line 2
    [1 if i <= 3 else 2 if i > 3 and i < 7 for i in a]
                                             ^
SyntaxError: invalid syntax

回答1:

List comprehension:

Add some more conditions :D (no this is really messy)

[
    1 if i <= 3 else 2
    for i in a
    if i != 4 and i < 7
]

How did we get here?

Basic list comp: [EXPRESSION for TARGET in ITERABLE if CONDITION]

Ternary expression: (IF_TRUE if CONDITION else IF_FALSE)

  1. Get the for loop in. Simple enough for i in a.
  2. Add conditions that filter out items which will be ignored. Once it gets past CONDITION, there has to be an item in the list at that position. In this case, we don't want i if it's 4 or greater than 7. if i != 4 and i < 7.
  3. Do what you need with the item. In this case, we want 1 if i is smaller or equal to 4. Otherwise, we'll take 2. 1 if i <= 3 else 2. Note: this is a ternary expression. Check them out!