Python - 从其他列表中保留 K 个匹配索引值
有时,在使用Python列表时,我们可能会遇到一个问题,即我们只需要保留与相同索引的相应列表中的特定值匹配的字符串。这可以在许多领域中应用。让我们讨论可以执行此任务的某些方式。
方法 #1:使用列表理解 + zip()
上述功能的组合可用于执行此任务。在此,我们在对匹配 K 的列表进行选择性压缩后提取列表。
# Python3 code to demonstrate
# Retain K match index values from other list
# using zip() + list comprehension
# Initializing lists
test_list1 = ['Gfg', 'is', 'best', 'for', 'Geeks', 'and', 'CS']
test_list2 = [4, 1, 4, 3, 4, 2, 4]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Initializing K
K = 4
# Group elements from Dual List Matrix
# using zip() + list comprehension
res = [x for x, y in zip(test_list1, test_list2) if y == K]
# printing result
print ("The filtered list : " + str(res))
输出 :
The original list 1 is : [‘Gfg’, ‘is’, ‘best’, ‘for’, ‘Geeks’, ‘and’, ‘CS’]
The original list 2 is : [4, 1, 4, 3, 4, 2, 4]
The filtered list : [‘Gfg’, ‘best’, ‘Geeks’, ‘CS’]
方法 #2:使用compress()
+ 列表推导
这是可以执行此任务的另一种方式。在此,我们使用 compress() 而不是 zip() 来解决问题。
# Python3 code to demonstrate
# Retain K match index values from other list
# using compress + list comprehension
from itertools import compress
# Initializing lists
test_list1 = ['Gfg', 'is', 'best', 'for', 'Geeks', 'and', 'CS']
test_list2 = [4, 1, 4, 3, 4, 2, 4]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Initializing K
K = 4
# Group elements from Dual List Matrix
# using compress + list comprehension
res = list(compress(test_list1, map(lambda ele: ele == K, test_list2)))
# printing result
print ("The filtered list : " + str(res))
输出 :
The original list 1 is : [‘Gfg’, ‘is’, ‘best’, ‘for’, ‘Geeks’, ‘and’, ‘CS’]
The original list 2 is : [4, 1, 4, 3, 4, 2, 4]
The filtered list : [‘Gfg’, ‘best’, ‘Geeks’, ‘CS’]