Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python replace tuples from list of tuples by highest priority list

I have those python lists :

x = [('D', 'F'), ('A', 'D'), ('B', 'G'), ('B', 'C'), ('A', 'B')]
priority_list = ['A', 'B', 'C', 'D', 'F', 'G'] # Ordered from highest to lowest priority

How can I, for each tuple in my list, keep the value with the highest priority according to priority_list? The result would be :

['D', 'A', 'B', 'B', 'A']

Another examples:

x = [('B', 'D'), ('E', 'A'), ('B', 'A'), ('D', 'F'), ('E', 'C')]
priority_list = ['A', 'B', 'C', 'D', 'E', 'F']
# Result:
['B', 'A', 'A', 'D', 'C']

x = [('B', 'C'), ('F', 'E'), ('B', 'A'), ('D', 'F'), ('E', 'C')]
priority_list = ['F', 'E', 'D', 'C', 'B', 'A'] # Notice the change in priorities
# Result:
['C', 'F', 'B', 'F', 'E']

Thanks in advance, I might be over complicating this.

like image 437
Waroulolz Avatar asked Dec 14 '22 10:12

Waroulolz


1 Answers

You can try

[sorted(i, key=priority_list.index)[0] for i in x]

though it will throw an exception if you find a value not in the priority list.

like image 185
tomjn Avatar answered Dec 29 '22 00:12

tomjn