在 Python 中获取匹配索引
给出两个列表。我们需要找到第一个列表中的元素的索引,其值与第二个列表中的元素匹配。
带索引
我们只需按照以下步骤获取第二个列表中元素的值,然后从第一个列表中提取相应的索引。
示例
listA = ['Mon','Tue', 'Wed', 'Thu', 'Fri']
listB = ['Tue', 'Fri']
# Given lists
print("The given list:\n ",listA)
print("The list of values:\n ",listB)
# using indices
res = [listA.index(i) for i in listB]
# Result
print("The Match indices list is : ",res)输出
运行上述代码,得到以下结果 -
The given list: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] The list of values: ['Tue', 'Fri'] The Match indices list is : [1, 4]
带枚举和集合
我们将设计一个 for 循环,它将使用 enumerate 提取所有元素,然后将其与成对的值匹配。最后,它将提取匹配的索引。
示例
listA = ['Mon','Tue', 'Wed', 'Thu', 'Fri']
listB = ['Tue', 'Fri']
# Given lists
print("The given list:\n ",listA)
print("The list of values:\n ",listB)
# using enumerate
res = [key for key, val in enumerate(listA)
if val in set(listB)]
# Result
print("The Match indices list is : ",res)输出
运行上述代码,得到以下结果 -
The given list: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] The list of values: ['Tue', 'Fri'] The Match indices list is : [1, 4]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP