Python - 行范围内的最大值
给定一个范围和一个矩阵,从该行范围中提取最大元素。
Input : test_list = [[4, 3, 6], [9, 1, 3], [4, 5, 2], [9, 10, 3], [5, 9, 12], [3, 14, 2]], i, j = 2, 5
Output : 12
Explanation : Checks for rows 2, 3 and 4, maximum element is 12.
Input : test_list = [[4, 3, 6], [9, 1, 3], [4, 5, 2], [9, 10, 3], [5, 9, 12], [3, 14, 2]], i, j = 1, 4
Output : 10
Explanation : Checks for rows 1, 2 and 3, maximum element is 10.
方法 #1:使用max() +切片
在这种情况下,我们执行对必须找到最大值的行进行切片的任务,然后使用 max() 为每一行找到最大值,应用另一个 max() 以在提取的元素上获得最大值。
Python3
# Python3 code to demonstrate working of
# Maximum in Rows Range
# Using max() + slicing
# initializing list
test_list = [[4, 3, 6], [9, 1, 3], [4, 5, 2],
[9, 10, 3], [5, 9, 12], [3, 14, 2]]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 2, 4
res = 0
for idx in range(i, j):
# getting max in range
res = max(max(test_list[idx]), res)
# printing result
print("The maximum element in row range ? : " + str(res))
Python3
# Python3 code to demonstrate working of
# Maximum in Rows Range
# Using max() + slicing + list comprehension
# initializing list
test_list = [[4, 3, 6], [9, 1, 3], [4, 5, 2],
[9, 10, 3], [5, 9, 12], [3, 14, 2]]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 2, 4
# getting max of maximum of sub lists
res = max([max(test_list[idx]) for idx in range(i, j)])
# printing result
print("The maximum element in row range ? : " + str(res))
输出:
The original list is : [[4, 3, 6], [9, 1, 3], [4, 5, 2], [9, 10, 3], [5, 9, 12], [3, 14, 2]]
The maximum element in row range ? : 10
方法 #2:使用 max() +切片 + 列表理解
在这种情况下,我们使用列表理解来执行与上述类似的任务,为该操作提供一个 liner。
蟒蛇3
# Python3 code to demonstrate working of
# Maximum in Rows Range
# Using max() + slicing + list comprehension
# initializing list
test_list = [[4, 3, 6], [9, 1, 3], [4, 5, 2],
[9, 10, 3], [5, 9, 12], [3, 14, 2]]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 2, 4
# getting max of maximum of sub lists
res = max([max(test_list[idx]) for idx in range(i, j)])
# printing result
print("The maximum element in row range ? : " + str(res))
输出:
The original list is : [[4, 3, 6], [9, 1, 3], [4, 5, 2], [9, 10, 3], [5, 9, 12], [3, 14, 2]]
The maximum element in row range ? : 10