简体   繁体   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

I'm looking for a string within a list of strings and the string to be found is a subset of one of the strings in the "search" list I need a way to get in which item of the list was the string found example:我正在字符串列表中查找字符串,要找到的字符串是“搜索”列表中字符串之一的子集,我需要一种方法来获取列表中的哪个项目是找到的字符串示例:

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

searchitem1 = 'pepe'

searchitem2 = 'sofi'

I tried:我试过:

     mylist.index('pepe')

but didn't work (as its not the exact string I guess?) I also tried:但没有用(因为它不是我猜的确切字符串?)我也尝试过:

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

but didn't work either.... What i'm looking at Is like stopping when the string is found and getting from the code in which item the find occurred....但也没有工作....我在看什么就像在找到字符串时停止并从找到的项目中的代码中获取....

thanks!谢谢!

You can write a function that will return when it finds the first index that contains the string your interested in. Alternativly if you want all indexs that contain the string you can use yield to create a generator that will produce all the indexs that contain the string.您可以编写一个函数,当它找到包含您感兴趣的字符串的第一个索引时将返回。或者,如果您想要包含该字符串的所有索引,您可以使用 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')))

OUTPUT输出

0
3
[0, 1, 2, 3]

If you are new to Python, maybe you are better by now with the classical approach in Chris answer.如果您不熟悉 Python,也许现在使用 Chris answer 中的经典方法会更好。 But if you feel curious about generators see the following example using a generator expression (essentially the same as Chris answer but more compact):但是,如果您对生成器感到好奇,请查看以下使用生成器表达式的示例(与 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
>>>

The indexes can be extracted as usual like in可以像往常一样提取索引

>>> next(gen)[0]

A generator object is always created even if there are no elements that match the if clause in the generator expression.即使在生成器表达式中没有与 if 子句匹配的元素,也始终会创建生成器对象。

To handle the exception when next() does not yield more values use a try block to capture the StopIteration :要在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.

相关问题 Python:如何检查列表中的项目是否在elif语句中的字符串中必须满足两个条件? - Python: How can I check if an item in a list contains a string within an elif statement where two conditions must be met? Python-搜索包含字符串的列表项(区分大小写) - Python - Search a list item that contains a string (match case) 如何使用.index在列表中的列表中搜索项目的位置? - How do I use .index to search for an item's position in list within a list? Python-如何检查字符串是否包含列表中的项目,并在返回true时,使列表中的项目作为索引在循环中可用 - Python - How to check whether a string contains an item from a list, and when returns true, have the item from the list as index usable in the loop 如何在python中的列表项中删除字符串 - How to remove a string within a list item in python 如何获取嵌套列表项的索引? - How can I get the index of a nested list item? 如何获取python列表中项目的索引和值? - How to get index and value of an item in python list? 如何在列表中搜索项目 - python - How can you search for an item in a list - python 如何使用 python 中的索引删除字符串列表中的项目 - how to remove an item in a list of list of string using index in python 如何在列表列表中搜索项目? - How can I search an item in a list of lists?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM