mardi 2 avril 2019

Way without nested ifs to make a non-empty list of tuples with a common second element based on custom preference?

I have a list of tuples (a,b) with b equal to 1,2, or 3. I want to make a list of a's where b == 2. If that list would be empty, I want to make a list of all a's where b == 1. Should that also be empty, then I want to make a list of all a's b == 3.

Right now I am using a nested if to accomplish this:

sizeTwo = (tup[0] for tup in tupleList if tup[1] == 2)
if sizeTwo:
        targetList = sizeTwo
else:
        sizeOne = (tup[0] for tup in tupleList if tup[1] == 1)
        if sizeOne:
                targetList = sizeOne
        else:
                sizeThree = (tup[0] for tup in tupleList if tup[1] == 3)
                if sizeThree: 
                        targetList = sizeThree
                else: 
                        print(f"Error: no matching items in tupleList")

Is there a "cleaner" way to accomplish this?




Aucun commentaire:

Enregistrer un commentaire