如何在 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/