python - 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' 类型的参数是不可迭代的
具体来说,我的问题是:如何通过在其中搜索特定子字符串来检索整个字符串并对其执行某些操作?
解决方案
您可以使用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
推荐阅读
- vba - 我无法检索网页上的信息
- android - Android Livedata 存储库单元测试问题
- image - 如何在文件对象的资产文件夹中加载图像?我收到一个错误“没有这样的文件或目录,errno = 2”
- c++ - CUDA 代码可以在 Linux 上编译,但不能在 Windows 上编译(Visual Studio 2012)
- r - 为不包括结果列的每个组合附加缺失的日期
- p5.js - 我的一个变量被无缘无故地改变了
- javascript - 如何保护自己免受 XSS 攻击,同时按照用户期望的方式显示字符?
- traffic-simulation - 使用 flow-project 对 OSM 数据进行模拟时,车辆消失
- laravel - Laravel,在关系中使用数据透视表
- c++ - 转换向量地址以复制数据