获取包含子字符串的第一个列表索引?
问题描述:
对于列表,方法list.index(x)
返回值为x
的第一项列表中的索引.但是,如果我要查看列表项而不是整个列表项,该如何最大程度地使用Pythoninc方法?
For lists, the method list.index(x)
returns the index in the list of the first item whose value is x
. But if I want to look inside the list items, and not just at the whole items, how do I make the most Pythoninc method for this?
例如,使用
l = ['the cat ate the mouse',
'the tiger ate the chicken',
'the horse ate the straw']
此函数将返回带有参数tiger
的1
.
this function would return 1
provided with the argument tiger
.
答
一种非光滑方法:
def index_containing_substring(the_list, substring):
for i, s in enumerate(the_list):
if substring in s:
return i
return -1