簡體   English   中英

如何在包含要在 python 中搜索的字符串(在列表中)的列表中獲取項目的索引

[英]how can I get the index of the item in a list that contains the string being search (within the list) in python

我正在字符串列表中查找字符串,要找到的字符串是“搜索”列表中字符串之一的子集,我需要一種方法來獲取列表中的哪個項目是找到的字符串示例:

mylist = ['hola pepe', 'hola manola', 'hola julian', 'holasofi']

searchitem1 = 'pepe'

searchitem2 = 'sofi'

我試過:

     mylist.index('pepe')

但沒有用(因為它不是我猜的確切字符串?)我也嘗試過:

    if any(ext in 'pepe' for ext in mylist): mylist.index(ext)

但也沒有工作....我在看什么就像在找到字符串時停止並從找到的項目中的代碼中獲取....

謝謝!

您可以編寫一個函數,當它找到包含您感興趣的字符串的第一個索引時將返回。或者,如果您想要包含該字符串的所有索引,您可以使用 yield 創建一個生成器,該生成器將生成包含該字符串的所有索引.

def get_first_index_contains(mylist, mystring):
    for index, element in enumerate(mylist):
        if mystring in element:
            return index

def get_all_index_contains(mylist, mystring):
    for index, element in enumerate(mylist):
        if mystring in element:
            yield index

mylist = ['hola pepe', 'hola manola', 'hola julian', 'holasofi']
searchitem1 = 'pepe'
searchitem2 = 'sofi'
print(get_first_index_contains(mylist, searchitem1))
print(get_first_index_contains(mylist, searchitem2))
print(list(get_all_index_contains(mylist, 'hola')))

輸出

0
3
[0, 1, 2, 3]

如果您不熟悉 Python,也許現在使用 Chris answer 中的經典方法會更好。 但是,如果您對生成器感到好奇,請查看以下使用生成器表達式的示例(與 Chris 的回答基本相同,但更緊湊):

>>> mylist = ['hola pepe', 'hola manola', 'hola julian', 'holasofi', 'oi pepe']
>>> gen = ((index,elem) for index, elem in enumerate(mylist) if 'pepe' in elem)
>>> next(gen)
(0, 'hola pepe')
>>> next(gen)
(4, 'oi pepe')
>>> next(gen)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>

可以像往常一樣提取索引

>>> next(gen)[0]

即使在生成器表達式中沒有與 if 子句匹配的元素,也始終會創建生成器對象。

要在next()沒有產生更多值時處理異常,請使用try塊來捕獲StopIteration

search = 'pepe'
...
try:
    next_result = next(gen)

except StopIteration:
    print('No more matches for {}'.format(search))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM