Python – 类似 K 的其他索引元素
给定元素列表、其他列表和 K,如果元素是列表中的 K,则提取所有相似的其他列表索引元素。
Input : test_list = [6, 4, 6, 3, 6], arg_list = [7, 5, 4, 6, 3], K = 6
Output : [7, 4, 3]
Explanation : 7, 4 and 3 correspond to occurrences of 6 in first list.
Input : test_list = [2, 3], arg_list = [4, 6], K = 3
Output : [6]
Explanation : 6 corresponds to only occurrence of 3.
方法 #1:使用 enumerate() + 列表理解
上述方法的组合提供了一种可以解决此任务的方法。在此,我们使用 enumerate() 从其他列表中检查类似索引,并使用列表推导创建新列表。
Python3
# Python3 code to demonstrate working of
# Similar other index element if K
# Using list comprehension + enumerate()
# initializing list
test_list = [5, 7, 3, 2, 3, 8, 6]
# printing original list
print("The original list : " + str(test_list))
# initializing arg. list
arg_list = [4, 5, 8, 3, 7, 9, 3]
# initializing K
K = 3
# Using enumerate() to locate similar index in other list and extract element
res = [ele for idx, ele in enumerate(arg_list) if test_list[idx] == K]
# printing result
print("Extracted elements : " + str(res))
Python3
# Python3 code to demonstrate working of
# Similar other index element if K
# Using list comprehension + zip()
# initializing list
test_list = [5, 7, 3, 2, 3, 8, 6]
# printing original list
print("The original list : " + str(test_list))
# initializing arg. list
arg_list = [4, 5, 8, 3, 7, 9, 3]
# initializing K
K = 3
# Using zip() to lock both the lists, with similar indices mapping
res = [ele for ele, ele1 in zip(arg_list, test_list) if ele1 == K]
# printing result
print("Extracted elements : " + str(res))
输出
The original list : [5, 7, 3, 2, 3, 8, 6]
Extracted elements : [8, 7]
方法 #2:使用列表理解 + zip()
上述功能的组合可以用来解决这个问题。在此,我们使用 zip() 将两个列表中的每个元素与其他元素进行组合。
Python3
# Python3 code to demonstrate working of
# Similar other index element if K
# Using list comprehension + zip()
# initializing list
test_list = [5, 7, 3, 2, 3, 8, 6]
# printing original list
print("The original list : " + str(test_list))
# initializing arg. list
arg_list = [4, 5, 8, 3, 7, 9, 3]
# initializing K
K = 3
# Using zip() to lock both the lists, with similar indices mapping
res = [ele for ele, ele1 in zip(arg_list, test_list) if ele1 == K]
# printing result
print("Extracted elements : " + str(res))
输出
The original list : [5, 7, 3, 2, 3, 8, 6]
Extracted elements : [8, 7]