获取包含子字符串的第一个列表索引? [英] Get first list index containing sub-string?

查看:77
本文介绍了获取包含子字符串的第一个列表索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于列表,方法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']

此函数将返回带有参数tiger1.

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

这篇关于获取包含子字符串的第一个列表索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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