📌  相关文章
📜  Python – 类似 K 的其他索引元素

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

Python – 类似 K 的其他索引元素

给定元素列表、其他列表和 K,如果元素是列表中的 K,则提取所有相似的其他列表索引元素。

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