获取包含子字符串的第一个列表索引?

时间:2023-01-21 15:15:20

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?

对于列表,方法list.index(x)返回值为x的第一个项的列表中的索引。但是如果我想查看列表项,而不仅仅是整个项目,我如何为此创建最多的Pythoninc方法?

For example, with

例如,用

l = ['the cat ate the mouse',
     'the tiger ate the chicken',
     'the horse ate the straw']

this function would return 1 provided with the argument tiger.

这个函数将返回1与参数tiger一起提供。

8 个解决方案

#1


27  

A non-slicky method:

一种非流畅的方法:

def index_containing_substring(the_list, substring):
    for i, s in enumerate(the_list):
        if substring in s:
              return i
    return -1

#2


4  

With a one-liner:

使用单线程:

index = [idx for idx, s in enumerate(l) if 'tiger' in s][0]

#3


3  

Variation of abyx solution (optimised to stop when the match is found)

abyx解决方案的变化(优化为在找到匹配时停止)

def first_substring(strings, substring):
    return next(i for i, string in enumerate(strings) if substring in string)

If you are pre 2.6 you'll need to put the next() at the end

如果您是2.6之前,则需要将next()放在最后

def first_substring(strings, substring):
    return (i for i, string in enumerate(strings) if substring in string).next()

#4


2  

def find(l, s):
    for i in range(len(l)):
        if l[i].find(s)!=-1:
            return i
    return None # Or -1

#5


2  

This is quite slick and fairly efficient.

这很光滑,效率很高。

>>> 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

Only problem is that it will raise StopIteration if the item is not found (though that is easily remedied).

唯一的问题是,如果找不到该项,它将引发StopIteration(虽然这很容易解决)。

#6


1  

def first_substring(strings, substring):
    return min(i for i, string in enumerate(strings) if substring in string)

Note: This will raise ValueError in case no match is found, which is better in my opinion.

注意:如果没有找到匹配,这将引发ValueError,这在我看来更好。

#7


1  

  >>> 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

#8


1  

imho with this line, you'll find only the first occurence without processing the whole list

imho用这一行,你会发现只有第一次出现而没有处理整个列表

index = next((i for i in enumerate(l) if "tiger" in i[1]),[-1,-1])[0]

index = next((i代表i枚举(l)如果i [1]中的“tiger”,[ - 1,-1])[0]

#1


27  

A non-slicky method:

一种非流畅的方法:

def index_containing_substring(the_list, substring):
    for i, s in enumerate(the_list):
        if substring in s:
              return i
    return -1

#2


4  

With a one-liner:

使用单线程:

index = [idx for idx, s in enumerate(l) if 'tiger' in s][0]

#3


3  

Variation of abyx solution (optimised to stop when the match is found)

abyx解决方案的变化(优化为在找到匹配时停止)

def first_substring(strings, substring):
    return next(i for i, string in enumerate(strings) if substring in string)

If you are pre 2.6 you'll need to put the next() at the end

如果您是2.6之前,则需要将next()放在最后

def first_substring(strings, substring):
    return (i for i, string in enumerate(strings) if substring in string).next()

#4


2  

def find(l, s):
    for i in range(len(l)):
        if l[i].find(s)!=-1:
            return i
    return None # Or -1

#5


2  

This is quite slick and fairly efficient.

这很光滑,效率很高。

>>> 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

Only problem is that it will raise StopIteration if the item is not found (though that is easily remedied).

唯一的问题是,如果找不到该项,它将引发StopIteration(虽然这很容易解决)。

#6


1  

def first_substring(strings, substring):
    return min(i for i, string in enumerate(strings) if substring in string)

Note: This will raise ValueError in case no match is found, which is better in my opinion.

注意:如果没有找到匹配,这将引发ValueError,这在我看来更好。

#7


1  

  >>> 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

#8


1  

imho with this line, you'll find only the first occurence without processing the whole list

imho用这一行,你会发现只有第一次出现而没有处理整个列表

index = next((i for i in enumerate(l) if "tiger" in i[1]),[-1,-1])[0]

index = next((i代表i枚举(l)如果i [1]中的“tiger”,[ - 1,-1])[0]