mercredi 15 juillet 2020

Looping nested lists through Boolean if-elif-else conditions

I plan to analyse legislation for the proportion of opposition, coalition or cross bench bills.

I have written two simple checks using any() to check if the inner list of parties who co-wrote a bill are found in the lists listing opposition and coalition parties.

coalition = ['CD&V', 'N-VA', 'Open Vld']
opposition = ['sp.a', 'Groen', 'Vlaams Belang', 'PVDA']

parties = [['Groen', 'sp.a'], ['CD&V', 'N-VA'], ['sp.a', 'CD&V']]   # test cases, one for each outcome

check_op = any(party in parties for party in opposition)
check_co = any(party in parties for party in coalition)

I then loop through the list of lists and perform the checks using if elif else

for p in parties:
    if check_op is True and check_co is False:
        print("This is an opposition bill")
    elif check_co is True and check_op is False:
        print("This is a coalition bill")
    elif check_co is True and check_op is True:
        print("This is a cross bench bill")
    else:
        print('none')

The result is always:

none
none
none

Whereas I would expect:

This is an opposition bill
This is a coalition bill
This is a cross bench bill

When I try to go through the conditions using just one list of parties, instead of looping through nested lists, the result comes out correctly...

What am I doing wrong, how can I get the for-loop to go through the conditions and get the correct result. Thank you.

Aucun commentaire:

Enregistrer un commentaire