Python - 其他列表中的最大 K 个元素
给定两个列表,提取对应列表中具有相似 K 的元素的最大值。
Input : test_list1 = [4, 3, 6, 2, 8], test_list2 = [3, 6, 3, 4, 3], K = 3
Output : 8
Explanation : Elements corresponding to 3 are, 4, 6, and 8, Max. is 8.
Input : test_list1 = [10, 3, 6, 2, 8], test_list2 = [5, 6, 5, 4, 5], K = 5
Output : 10
Explanation : Elements corresponding to 5 are, 10, 6, and 8, Max. is 10.
方法 #1:使用循环 + max()
在此,我们从列表 1 中提取所有等于列表 2 中 K 的元素,然后执行 max() 以获取它们中的最大值。
Python3
# Python3 code to demonstrate working of
# Maximum of K element in other list
# Using loop + max()
# initializing lists
test_list1 = [4, 3, 6, 2, 9]
test_list2 = [3, 6, 3, 4, 3]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing K
K = 3
res = []
for idx in range(len(test_list1)):
# checking for K in 2nd list
if test_list2[idx] == K :
res.append(test_list1[idx])
# getting Maximum element
res = max(res)
# printing result
print("Extracted Maximum element : " + str(res))
Python3
# Python3 code to demonstrate working of
# Maximum of K element in other list
# Using list comprehension + max() + zip()
# initializing lists
test_list1 = [4, 3, 6, 2, 9]
test_list2 = [3, 6, 3, 4, 3]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing K
K = 3
# one liner to solve this problem
res = max([sub1 for sub1, sub2 in zip(test_list1, test_list2) if sub2 == K])
# printing result
print("Extracted Maximum element : " + str(res))
输出
The original list 1 is : [4, 3, 6, 2, 9]
The original list 2 is : [3, 6, 3, 4, 3]
Extracted Maximum element : 9
方法 #2:列表理解 + max() + zip()
在此,我们使用 zip() 执行配对元素的任务,并且是使用列表理解提供的单线解决方案。
Python3
# Python3 code to demonstrate working of
# Maximum of K element in other list
# Using list comprehension + max() + zip()
# initializing lists
test_list1 = [4, 3, 6, 2, 9]
test_list2 = [3, 6, 3, 4, 3]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing K
K = 3
# one liner to solve this problem
res = max([sub1 for sub1, sub2 in zip(test_list1, test_list2) if sub2 == K])
# printing result
print("Extracted Maximum element : " + str(res))
输出
The original list 1 is : [4, 3, 6, 2, 9]
The original list 2 is : [3, 6, 3, 4, 3]
Extracted Maximum element : 9