# 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.

Tags :

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=='<'],key=lambda x: x),max([i for i in mylist if i=='>'],key=lambda x: x)]

print(ls)
``````

Also you can try this using `sorted`:

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

Both outputs:

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

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)]
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()
``````

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 == '<', mylist)), max(filter(lambda x:x == '>', mylist))]
``````

could do this with two quick lines like this:

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

print(upper, lower)

output:

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