python - 匹配两个列表之间的元素,但索引为索引
问题描述
可以说我有这两个列表:
lst1 = ['A1','B1','C1']
lst2 = ['A1','B2']
对于 lst1 中的每个元素,按索引与 lst2 中的相应元素进行比较(1-1 而不是元素 1 到 lst2 中的所有元素)。如果找到匹配项,则打印如下输出:
'match found between A1 and A1 at index 0 in both lists'
如果元素与这样的输出不匹配,则应给出:
'Elements at index 1 do not match"
如果 lst1 中索引 2 处的元素在 lst2 中没有对应的索引,则打印输出:
'For element at index 3, 'C1', no corresponding match found in lst3.
我试过的:
for i in range(len(lst1)):
if lst1[i] == lst2[i]:
return 'Match between...'
else:
return 'Not matched...'
当列表的长度不匹配时,它会失败,除此之外,我确信有一种更聪明的方法可以做到这一点。
解决方案
试试这个:
lst1 = ['A1','B1','C1']
lst2 = ['A1','B2']
max_length = max(len(lst1), len(lst2))
for i in range(max_length):
try:
if lst1[i] == lst2[i]:
print(f'match found between {lst1[i]} and {lst2[i]} at index {i} in both lists')
else:
print(f"Elements at index {i} do not match")
except:
if len(lst1) >= i:
print(f"For element at index {i}, {lst1[i]}, no corresponding match found in lst2.")
else:
print(f"For element at index {i}, no corresponding match found in lst2. {lst2[i]}")
这将产生这个输出:
match found between A1 and A1 at index 0 in both lists
Elements at index 1 do not match
For element at index 2, C1, no corresponding match found in lst2.
推荐阅读
- android-architecture-components - View.findNavController() 与 Fragment.findNavController()
- neo4j - Neo4j 无法在 Windows 7 上启动(在 Windows 10 上正常)
- c - sigaction 将 SIGINT 传递给系统调用,但不传递信号
- codeigniter - 为什么 Codeigniter 使用分页在每个页面上显示相同的数据?
- google-apps-script - “com.au”字符串在脚本编辑器中显示为“(class)”
- twig - 条件模板继承在 Symfony 4 中不起作用
- websocket - 如何在 Google Kubernetes Engine 中设置 websocket
- php - 无法通过 codeclimate 在 phpmd 上更改 ExcessiveMethodLength
- php - 在 php 中加密并在 Dart(flutter) 中解密
- firebase - 为什么电子邮件密码示例有效?