Home > OS >  Is it possible to set a priority to elements in a list?
Is it possible to set a priority to elements in a list?

Time:08-19

i'm trying to set a priority for each element in my list, here is the code :

mylist = []

state0 = [True, 2]
state1 = [False, 2]
state2 = [True, 3]
state3 = [True, 4]
state4 = [False, 3]

mylist.append(state0)
mylist.append(state1)
mylist.append(state2)
mylist.append(state3)
mylist.append(state4)



def function():
    for element, priority in mylist:
        if element is False and ...: # And priority is higher than the others
            
function()

The fact here, is that I need to retrieve an element in mylist that is False and its priority is higher than all the elements in mylist.

I don't know if there is a pythonic way to do that. If you have any idea, i'll take it !

Thanks in advance.

CodePudding user response:

You can use max with key base numbers, then find the max number and check if base max number.

from operator import itemgetter
max_num = max(mylist, key=itemgetter(1))[1]
# max(mylist, key=itemgetter(1)) -> [True, 4] 
# [True, 4][1] -> 4

def function(mylist):
    max_num = max(mylist, key=itemgetter(1))[1]
    for element, priority in mylist:
        if element is False and priority > max_num: # And priority is higher than the others
            # Do waht you want
            
function(mylist)

CodePudding user response:

You could make use of filter (remove True's) and sort by priority, so the first element of the sorted list has a high priority than the other ones:

mylist = [[True, 2], [False, 2], [True, 3], [True, 4], [False, 3]]

mylist = filter(lambda x: x[0] == False, mylist)  # Keep all falses
print(
    sorted(mylist, key=lambda x: (x[0], x[1]), reverse=1)[0]
)  # sort by priority

Out:

[False, 3]

CodePudding user response:

If you make your priority values negative, you can simply use min() to retrieve the element you want. Or if not, use a custom key argument to min() or max() to make the lowest-value-but-highest-priority element come out first, for example:

selected = min(mylist,  key=lambda x:[x[0],-x[1]] )
print(selected is state4)    #  prints True
if selected[0] == False:
    do_something_with( selected )

Your question implies you want to process just the one element whose priority is greatest. But if you want to process more, you can also do mylist.sort( key=... ) so that all the Falsies come out earlier than all the Truthies, in priority order.

  • Related