如何在Python中循环列表

如何在Python中循环列表,python,list,loops,Python,List,Loops,如何在Python中循环列表。我尝试在示例列表中为ch使用,,但它只遍历列表中的一项 sample_list = ['abc', 'def', 'ghi', 'hello'] for ch in sample_list: if ch == 'hello': return ch 如何使其工作?return终止函数,为避免此情况,您可以使用print(或yield;创建生成器): 但是,对于此特定示例,您应该使用any()或list.count()(具体取

如何在Python中循环列表。我尝试在示例列表中为ch使用
,但它只遍历列表中的一项

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

如何使其工作?

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

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

试试这个

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

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


我希望这有助于

正如@Chris_Rands所说,你可以使用收益率

def loopList():
    sample_list = ['abc', 'def', 'ghi', 'hello']
    for ch in sample_list:
        if ch == 'hello':
            yield ch
您应该知道,收益率返回的是生成器而不是列表

但是,您也可以创建一个包含结果的新列表

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

    return results

return
终止函数,您想要
print
(或
yield
)请阅读,您能看到返回时您和@Diblo解决方案之间的差异吗?改变这一点,我将投票表决up@AriGold,废弃了那部分,还没看到-谢谢如果这是你的清单会发生什么:['hello','abc','def','ghi','hello'],会有什么回报?请更改该问题,以便我们需要将所有出现的单词“hello”附加到say a列表中。明白了。我认为这将与@Diblo的解决方案相同
def loopList():
    sample_list = ['abc', 'def', 'ghi', 'hello']
    for ch in sample_list:
        if ch == 'hello':
            yield ch
def loopList():
    sample_list = ['abc', 'def', 'ghi', 'hello']
    results = []
    for ch in sample_list:
        if ch == 'hello':
            result.append(ch)

    return results