Python list of conditions to single condition

by Mustard Tiger   Last Updated June 30, 2020 02:26 AM

I have a list of conditions such as the following:

mylist = [['<', 1000], ['<', 100],['<', 25],['>', 10],['>', 5]]

The result would be:

mylist = [['<', 25],['>', 10]]

Essentially it would take the smallest number of the '<' condition and or the largest number of the '>' condition.

What would be the best way to go about this?



Answers 4


You could try this with min, max and list comprehension:

mylist = [['<', 1000], ['<', 100],['<', 25],['>', 10],['>', 5]]

ls=[min([i for i in mylist if i[0]=='<'],key=lambda x: x[1]),max([i for i in mylist if i[0]=='>'],key=lambda x: x[1])]

print(ls)

Also you can try this using sorted:

mylist = [['<', 1000], ['<', 100],['<', 25],['>', 100],['>', 5]]
ls=[sorted(mylist,key=lambda x: (x[0],x[1]))[0],sorted(mylist,key=lambda x: (x[0],x[1]))[-1]]
print(ls)

Both outputs:

[['<', 25], ['>', 10]]
MrNobody33
MrNobody33
June 30, 2020 01:57 AM

You can use itertools.groupby to group by the operator and then find the min/max of the second value as appropriate:

import itertools

mylist = [['<', 1000], ['<', 100],['<', 25],['>', 10],['>', 5]]

out = [min(g) if k == '<' else max(g) for k, g in itertools.groupby(mylist, key=lambda l:l[0])]
print(out)

Output:

[['<', 25], ['>', 10]]

Note

If your list is not already sorted by operator, you should sort it prior to using groupby using list.sort:

mylist.sort()
Nick
Nick
June 30, 2020 01:58 AM

You can use min and max, after first filtering the target list with filter:

mylist = [['<', 1000], ['<', 100],['<', 25],['>', 10],['>', 5]]
result = [min(filter(lambda x:x[0] == '<', mylist)), max(filter(lambda x:x[0] == '>', mylist))]
Ajax1234
Ajax1234
June 30, 2020 01:58 AM

could do this with two quick lines like this:

lower = sorted([ele for ele in mylist if '>' in ele], key=lambda x:x[1])[-1]
upper = sorted([ele for ele in mylist if '<' in ele], key=lambda x:x[1])[0]

print(upper, lower)

output:

['<', 25] ['>', 10]
Derek Eden
Derek Eden
June 30, 2020 02:25 AM

Related Questions


Python Ignoring Conditional Statement

Updated June 24, 2020 04:26 AM


How to make conditions that depends on one statement

Updated September 01, 2019 05:26 AM

how can i fix this filter function till it works?

Updated September 02, 2019 04:26 AM