Python find min & max of two lists

2020-04-02 06:41发布

I have two lists such as:

l_one = [2,5,7,9,3]
l_two = [4,6,9,11,4]

...and I need to find the min and max value from both lists combined. That is, I want to generate a single min and a single max value.

My question is - what is the most pythonic way to achieve this?

Any help much appreciated.

标签: python list
5条回答
啃猪蹄的小仙女
2楼-- · 2020-04-02 06:59

Arguably the most readable way is

max(l_one + l_two)

or

min(l_one + l_two)

It will copy the lists, though, since l_one + l_two creates a new list. To avoid copying, you could do

max(max(l_one), max(l_two))
min(min(l_one), min(l_two))
查看更多
叼着烟拽天下
3楼-- · 2020-04-02 07:02

If you want to select the maximum or minimum values from the two lists.I think the following will work:

from numpy import maximum
result = maximum(l_one,l_two)

It will return a maximum value after comparing each element in this two lists.

查看更多
唯我独甜
4楼-- · 2020-04-02 07:09

Another way that avoids copying the lists

>>> l_one = [2,5,7,9,3]
>>> l_two = [4,6,9,11,4]
>>> 
>>> from itertools import chain
>>> max(chain(l_one, l_two))
11
>>> min(chain(l_one, l_two))
2
查看更多
够拽才男人
5楼-- · 2020-04-02 07:17

if you just have lists like you do, this works, even with lists from different sizes :

min(min([i1,i2,i3]))

You may even have a smarter solution which works with different numpy array :

import numpy as np
i1=np.array(range(5))
i2=np.array(range(4))
i3=np.array(range(-5,5))
np.min(np.concatenate([i1,i2,i3]))
查看更多
手持菜刀,她持情操
6楼-- · 2020-04-02 07:19

You can combine them and then call min or max:

>>> l_one = [2,5,7,9,3]
>>> l_two = [4,6,9,11,4]
>>> min(l_one + l_two)
2
>>> max(l_one + l_two)
11
查看更多
登录 后发表回答