在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循环,该循环将使用枚举来提取所有元素,然后将它们与键值对匹配。最后,它将提取匹配的索引。
示例
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]
热门推荐
5 短祝福语简短暖心
10 结婚祝福语粤语大全简短
11 晚上祝福语女生文案简短
12 法语妈妈生日祝福语简短
13 药厂开工祝福语大全简短
14 蛋糕节日祝福语简短英文
15 跨年的生日祝福语简短
16 文案祝福语英文短句简短
17 在家聚餐婚礼祝福语简短
18 学生节祝福语大全简短