在其他列表项中查找列表项的列表索引 [英] Find list index of list items within other list items

查看:100
本文介绍了在其他列表项中查找列表项的列表索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个长字符串列表,我想获取与另一个列表中的字符串子字符串匹配的列表元素的索引.使用列表推导,很容易检查列表项是否在列表中包含单个字符串,例如

I have a list of long strings and I'd like to get the indexes of the list elements that match a substring of strings in another list. Checking if a list item contains a a single string inside a list is easy to do with list comprehensions, like this question:

my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
thing_to_find = "abc"
matching = [i for i, x in enumerate(my_list) if thing_to_find in x]

但是,我不仅要检查"abc"是否在x中,还要检查另一个列表中是否有任何字符串,例如:

However, I'd like to check not only if "abc" is in x, but if any strings in another list are in the list, like so:

my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
things_to_find = ['abc', 'def']

这显然是行不通的(但是如果这样做的话,那真的很酷):

This obviously doesn't work (but it would be really cool if it did):

matching = [i for i, x in enumerate(my_list) if things_to_find in x]

如果我单独运行命令,我可以找到列表索引,但这很乏味和可怕:

I can find the list indexes if I run commands individually, but it's tedious and horrible:

print([i for i, x in enumerate(my_list) if 'abc' in x])
# [0, 3]
print([i for i, x in enumerate(my_list) if 'def' in x])
# [1]

查找在一个列表中的元素位于另一列表中的所有实例的索引的最佳方法是什么?

What's the best way to find the indexes of all instances where elements from one list are found in another list?

推荐答案

您正在这里寻找any()函数:

matching = [i for i, x in enumerate(my_list) if any(thing in x for thing in things_to_find)]

演示:

>>> my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
>>> things_to_find = ['abc', 'def']
>>> [i for i, x in enumerate(my_list) if any(thing in x for thing in things_to_find)]
[0, 1, 3]

这篇关于在其他列表项中查找列表项的列表索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆