Python 是否获取包含子字符串的第一个列表索引?
对于列表,方法Python 是否获取包含子字符串的第一个列表索引?,python,list,Python,List,对于列表,方法list.index(x)返回值为x的第一项列表中的索引。但是,如果我想查看列表项内部,而不仅仅是整个项目,那么如何使用最适合的Pythoninc方法呢 例如,与 l = ['the cat ate the mouse', 'the tiger ate the chicken', 'the horse ate the straw'] 此函数将返回参数tiger提供的1,这是一种非光滑的方法: def index_containing_substring(the
list.index(x)
返回值为x
的第一项列表中的索引。但是,如果我想查看列表项内部,而不仅仅是整个项目,那么如何使用最适合的Pythoninc方法呢
例如,与
l = ['the cat ate the mouse',
'the tiger ate the chicken',
'the horse ate the straw']
此函数将返回参数tiger
提供的1
,这是一种非光滑的方法:
def index_containing_substring(the_list, substring):
for i, s in enumerate(the_list):
if substring in s:
return i
return -1
这是相当圆滑和相当有效的
>>> def find(lst, predicate):
... return (i for i, j in enumerate(lst) if predicate(j)).next()
...
>>> l = ['the cat ate the mouse','the tiger ate the chicken','the horse ate the straw']
>>> find(l, lambda x: 'tiger' in x)
1
唯一的问题是,如果找不到项,它将引发StopIteration(尽管这很容易修复)
注意:如果没有找到匹配项,这将引发
ValueError
,我认为这是更好的选择。abyx解决方案的变化(优化为在找到匹配项时停止)
如果您是2.6之前的版本,则需要将next()
放在末尾
def first_substring(strings, substring):
return (i for i, string in enumerate(strings) if substring in string).next()
使用一个班轮:
index = [idx for idx, s in enumerate(l) if 'tiger' in s][0]
有了这一行,您将只找到第一次出现,而不处理整个列表
index=next((如果i[1]中的“tiger”,则枚举(l)中的i为i),[-1,-1])[0]
使用映射函数:
index=np.nonzero(映射(lambda x:x中的子字符串,字符串))[0][0]
别出心裁,但效率不高,因为它会测试列表中的所有元素,而不管之前是否找到了文本。另外,Python的“something.find(s)函数在没有找到匹配项时返回-1,所以我将调用Pythonic.not,至少在Python2.6中是这样。在min()
中不能同时使用iterable和额外参数@Etienne:这是一个生成器表达式,不是列表理解,所以它不会生成所有内容。@Etienne-过早优化是万恶之源等@Max-你是对的,修复了。StopIteration可以避免:返回下一步((i代表i,j在枚举(lst)if谓词(j)),-1)
(Python 2.6+)
def first_substring(strings, substring):
return next(i for i, string in enumerate(strings) if substring in string)
def first_substring(strings, substring):
return (i for i, string in enumerate(strings) if substring in string).next()
>>> li = ['my','array','with','words']
>>> reduce(lambda tup, word: (tup[0], True) if not tup[1] and word == 'my' else (tup[0]+1 if not tup[1] else tup[0], tup[1]), li, (0, False))[0]
0
>>> reduce(lambda tup, word: (tup[0], True) if not tup[1] and word == 'words' else (tup[0]+1 if not tup[1] else tup[0], tup[1]), li, (0, False))[0]
3
index = [idx for idx, s in enumerate(l) if 'tiger' in s][0]