如何在Python中循环列表

2024-04-25 00:43:56 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在Python中循环列表。我试过使用for ch in sample_list,但它只遍历列表中的一个项目。你知道吗

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

我该怎么做?你知道吗


Tags: sample项目inhello列表forreturnif
3条回答

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

试试这个

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

显然return语句主要用于将控件返回给调用方函数的函数中 除非在函数中使用它。你宁愿使用打印功能

我希望这有帮助

正如@Chris\u Rands所说,你可以使用yield。你知道吗

def loopList():
    sample_list = ['abc', 'def', 'ghi', 'hello']
    for ch in sample_list:
        if ch == 'hello':
            yield ch

您应该知道,yield返回的是一个生成器,而不是一个列表。你知道吗

但是,您也可以创建一个包含结果的新列表。你知道吗

def loopList():
    sample_list = ['abc', 'def', 'ghi', 'hello']
    results = []
    for ch in sample_list:
        if ch == 'hello':
            result.append(ch)

    return results

相关问题 更多 >