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?

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

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

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

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

- ServerfaultXchanger
- SuperuserXchanger
- UbuntuXchanger
- WebappsXchanger
- WebmastersXchanger
- ProgrammersXchanger
- DbaXchanger
- DrupalXchanger
- WordpressXchanger
- MagentoXchanger
- JoomlaXchanger
- AndroidXchanger
- AppleXchanger
- GameXchanger
- GamingXchanger
- BlenderXchanger
- UxXchanger
- CookingXchanger
- PhotoXchanger
- StatsXchanger
- MathXchanger
- DiyXchanger
- GisXchanger
- TexXchanger
- MetaXchanger
- ElectronicsXchanger
- StackoverflowXchanger
- BitcoinXchanger
- EthereumXcanger