繁体   English   中英

查找两个长度不同的列表之间所有匹配项的索引

[英]find the indices for all matching items between two lists of different lengths

我正在尝试查找两个长度不同的列表之间所有匹配项的索引。

我创建了一个列表理解来比较两个列表:

 my_list = ["a123", "b456", "c234", "a134", "d567", "e789", "c278"] match_str = ["a1", "c2"] mod_list = [i for i in my_list if any([j in i for j in match_str])] 

输出在哪里
mod_list = ['a123','c234','a134','c278']

但是,当我尝试使用此枚举方法获取相应的索引时,出现错误消息:

 list_idx = [i for i, x in enumerate(my_list) if x == any([j in i for j in match_str])] 
TypeError:“ int”类型的参数不可迭代

我不确定是什么导致了错误。

我是正确解决这个问题还是有更好的方法? (我想不使用循环就可以做到这一点)

这是因为您的代码正在索引i上迭代! 您需要将其更改为x并删除x ==

>>> list_idx = [i for i, x in enumerate(my_list) if x == any([j in i for j in match_str])]
                                                                   ^

更改为:

>>> list_idx = [i for i, x in enumerate(my_list) if any([j in x for j in match_str])]
>>> list_idx
[0, 2, 3, 6]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM