Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select priority item from list

Tags:

python

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?

like image 663
Tristan Tran Avatar asked Sep 06 '25 03:09

Tristan Tran


1 Answers

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
like image 149
rdas Avatar answered Sep 07 '25 21:09

rdas