本文介绍了获取包含子字符串的第一个列表索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于列表,方法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
这篇关于获取包含子字符串的第一个列表索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!