Say I have a descending ordered list in terms of preference:
person_choice = ['amy', 'bob', 'chad', 'dan', 'emily']
meaning, amy
is preferred to bob
, who is preferred to chad
and so on.
And I have a couple more lists like these (with names appearing in no particular order and list length):
group1 = ['joyce', 'amy', 'emily', 'karen', 'rebecca']
group2 = ['chad', 'kyle', 'michael', 'neo', 'bob']
...
In each of the group1
and group2
, I would like to select the person within this list that appears in person_choice
with the highest preference. So, an expected output is like this:
group1_choice = 'amy'
group2_choice = 'bob'
Assuming that for each groupX
, there is at least one person appearing in person_choice
, is there a one-liner to do this in Python without complicated for
loop?
Using max
with a custom key
:
person_choice = ['amy', 'bob', 'chad', 'dan', 'emily']
group1 = ['joyce', 'amy', 'emily', 'karen', 'rebecca']
group2 = ['chad', 'kyle', 'michael', 'neo', 'bob']
def choice(group):
return max(group, key=lambda name: -person_choice.index(name) if name in person_choice else float('-inf'))
print(choice(group1))
print(choice(group2))
Result:
amy
bob
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With