首页 > 解决方案 > Python:需要帮助在列表中搜索子字符串

问题描述

我知道这是一个简单的问题,但我有一个包含数百个字符串的列表,我需要帮助来尝试选择其中的一些。例如,列表是:

lines = ["First Sentence dog", "Second Sentence dog", "Third Sentence cat", "Fourth Sentence cat"...]

我需要访问和操作包含单词“dog”的索引。我到目前为止的代码是:

    for line in range(len(lines)):
        if "dog" in line:
            # Do some something
        elif "cat" in line:
            # Do some something else
        else:
            # Do other things

感谢您的任何帮助!

编辑:我得到的错误是 TypeError:'int' 类型的参数是不可迭代的

具体来说,我的问题是:如何通过在其中搜索特定子字符串来检索整个字符串并对其执行某些操作?

标签: pythonpython-3.xlistfor-loop

解决方案


您可以使用enumerate()

for i,line in enumerate(lines):
    if "dog" in line:
        # Do some something
    elif "cat" in line:
        # Do some something else
    else:
        # Do other things

enumerate()将允许您迭代一个可迭代对象以及当前元素的索引。如果您不需要索引,只需:

for line in lines:
    if "dog" in line:
        # Do some something
    elif "cat" in line:
        # Do some something else
    else:
        # Do other things

推荐阅读