📌  相关文章
📜  Python - 其他列表中的最大 K 个元素

📅  最后修改于: 2022-05-13 01:55:22.811000             🧑  作者: Mango

Python - 其他列表中的最大 K 个元素

给定两个列表,提取对应列表中具有相似 K 的元素的最大值。

方法 #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