Python – 具有最大记录元素的行
有时,在使用Python Records 时,我们可能会遇到需要找到具有最大记录元素的行的问题。这类问题可能出现在 Web 开发和日常编程领域。让我们讨论可以执行此任务的某些方式。
Input : test_list = [[(70, 4), (6, 7)], [(15, 2), (19, 3)]]
Output : [(70, 4), (6, 7)]
Input : test_list = [[(20, 4)], [(15, 2)], [(34, 6)]]
Output : [(34, 6)]
方法#1:使用max()
+ key
上述功能的组合可以用来解决这个问题。在此,我们使用 max() 提取最大行,并使用 key 来检查记录的初始元素。
# Python3 code to demonstrate working of
# Row with Maximum Record Element
# Using max() + key
# initializing list
test_list = [[(12, 4), (6, 7)],
[(15, 2), (19, 3)],
[(18, 3), (12, 4)],
[(17, 1), (11, 3)]]
# printing original list
print("The original list is : " + str(test_list))
# Row with Maximum Record Element
# Using max() + key
res = max(test_list, key = max)
# printing result
print("The row with Maximum Value : " + str(res))
The original list is : [[(12, 4), (6, 7)], [(15, 2), (19, 3)], [(18, 3), (12, 4)], [(17, 1), (11, 3)]]
The row with Maximum Value : [(15, 2), (19, 3)]
方法 #2:使用max() + itemgetter()
这是解决此问题的另一种方法。这种方法提供了选择元素索引进行比较的灵活性,而不是像上述方法中使用 itemgetter() 的初始值。
# Python3 code to demonstrate working of
# Row with Maximum Record Element
# Using max() + itemgetter()
from operator import itemgetter
# initializing list
test_list = [[(12, 4), (6, 7)],
[(15, 2), (19, 3)],
[(18, 3), (12, 4)],
[(17, 1), (11, 3)]]
# printing original list
print("The original list is : " + str(test_list))
# Row with Maximum Record Element
# Using max() + itemgetter()
res = max(test_list, key = itemgetter(1))
# printing result
print("The row with Maximum Value : " + str(res))
The original list is : [[(12, 4), (6, 7)], [(15, 2), (19, 3)], [(18, 3), (12, 4)], [(17, 1), (11, 3)]]
The row with Maximum Value : [(15, 2), (19, 3)]