Python|两个列表中的最大值和最小值
在列表中找到最大值和最小值的问题很常见。但有时这个问题可以扩展为两个列表,因此成为一个修改后的问题。本文讨论了可以轻松执行此任务的速记。让我们讨论一些可以解决这个问题的方法。
方法 #1:使用 max() + min() + “ +
”运算符
最大值和最小值可以通过Python的常规 max 和 min函数确定,并且可以使用“ +
”运算符处理一到两个列表的扩展。
# Python3 code to demonstrate
# maximum and minimum values in two lists
# using max() + min() + "+" operator
# initializing lists
test_list1 = [1, 3, 4, 5, 2, 6]
test_list2 = [3, 4, 8, 3, 10, 1]
# printing the original lists
print ("The original list 1 is : " + str(test_list1))
print ("The original list 2 is : " + str(test_list2))
# using max() + min() + "+" operator
# maximum and minimum values in two lists
max_all = max(test_list1 + test_list2)
min_all = min(test_list1 + test_list2)
# printing result
print ("The maximum of both lists is : " + str(max_all))
print ("The minimum of both lists is : " + str(min_all))
输出:
The original list 1 is : [1, 3, 4, 5, 2, 6]
The original list 2 is : [3, 4, 8, 3, 10, 1]
The maximum of both lists is : 10
The minimum of both lists is : 1
方法 #2:使用max() + min() + chain()
执行此特定任务的另一种方法是使用链函数,该函数执行类似于“+”运算符但使用迭代器的任务,因此速度更快。
# Python3 code to demonstrate
# maximum and minimum values in two lists
# using max() + min() + "+" operator
from itertools import chain
# initializing lists
test_list1 = [1, 3, 4, 5, 2, 6]
test_list2 = [3, 4, 8, 3, 10, 1]
# printing the original lists
print ("The original list 1 is : " + str(test_list1))
print ("The original list 2 is : " + str(test_list2))
# using max() + min() + "+" operator
# maximum and minimum values in two lists
max_all = max(chain(test_list1, test_list2))
min_all = min(chain(test_list1, test_list2))
# printing result
print ("The maximum of both lists is : " + str(max_all))
print ("The minimum of both lists is : " + str(min_all))
输出:
The original list 1 is : [1, 3, 4, 5, 2, 6]
The original list 2 is : [3, 4, 8, 3, 10, 1]
The maximum of both lists is : 10
The minimum of both lists is : 1