vendredi 28 février 2020

Iterating inside an IF statement conditioned by a list in Python

Suppose I have a df:

     Name    Surname  Age
0    Alex    Jackson   10
1     Bob      Black   12
2  Clarke  Flingston   13
3  Claude      White   11
4   Julia     Waters   10
5  Robert    Ferrari   12
6    Anna        Red    9
7   David       Blue   10
8    Luke        Man   12

and with:

list_n = []
for age, surname in zip(df.Age, df.Surname):
    if (age != 13 and 
        age != 11 and 
        age != 10):
        list_n.append(surname)

list_n
['Black', 'Ferrari', 'Red', 'Man']

I get a list of surnames excluding the ones with a certain age. Is it possible to iterate the if condition with a list of ages?

I tried with list comprehension but it does not work as it should be:

list_age = [13,11,10]
list_n = []

for age, surname in zip(df.Age, df.Surname):
    [list_n.append(surname) for x in list_Age if age != x]

list_n
['Jackson', 'Jackson',  'Black',  'Black',  'Black', 'Flingston',
 'Flingston',  'White',  'White',  'Waters',  'Waters',  'Ferrari',
 'Ferrari',  'Ferrari',  'Red',  'Red',  'Red',  'Blue',  'Blue',
 'Man',  'Man',   'Man']

Aucun commentaire:

Enregistrer un commentaire