python - 如何在 Python 中循环列表

标签 python list loops

如何在 Python 中循环列表。我尝试使用 for ch in sample_list 但它只遍历列表中的一项。

sample_list = ['abc', 'def', 'ghi', 'hello']
for ch in sample_list:
       if ch == 'hello':
              return ch

如何让它发挥作用?

最佳答案

return 终止函数,为了避免这种情况,您可以使用 print (或 yield;它创建一个生成器):

>>> sample_list = ['abc', 'def', 'ghi', 'hello']
>>> for ch in sample_list:
...     if ch == 'hello':
...          print(ch)
... 
hello

但是,对于这个特定的示例,您应该使用 any()list.count() (具体取决于您接下来要执行的操作):

>>> any(item == 'hello' for item in sample_list)
True
>>> sample_list.count('hello')
1

关于python - 如何在 Python 中循环列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41064115/

相关文章:

python - 在 Python 中以特定顺序将列表值从列表插入到另一个列表

php - 如果在循环中包含 PHP 中的文件,每次在循环中运行时它都会访问该文件吗?

linux - 通过从文件中的每一行获取两个参数来循环的 Shell(bash) 脚本

python - 如何在循环 Python 中调用不同的函数

python - 放在 QMainWindow 的 Central Widget 中的 QTabWidget 拉伸(stretch)太多,覆盖了菜单栏

python - 如何找到字典和列表之间的匹配项以从匹配项创建新列表?

python - Django:您正在尝试添加一个不可为空的字段 'slug' 以在没有默认值的情况下发布;我们不能那样做

python - 迭代有效地计算平均值

python - 使 Django URL 使用或不使用/

python - 练习 14 艰难地学习 Python