2024-04-25 00:43:56 发布
网友
如何在Python中循环列表。我试过使用for ch in sample_list,但它只遍历列表中的一个项目。你知道吗
for ch in sample_list
sample_list = ['abc', 'def', 'ghi', 'hello'] for ch in sample_list: if ch == 'hello': return ch
我该怎么做?你知道吗
return终止函数,为了避免这种情况,可以使用print(或yield;它创建了一个生成器):
return
print
yield
>>> sample_list = ['abc', 'def', 'ghi', 'hello'] >>> for ch in sample_list: ... if ch == 'hello': ... print(ch) ... hello
但是,对于这个特定的示例,应该使用any()或list.count()(具体取决于接下来要做什么):
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
return
终止函数,为了避免这种情况,可以使用print
(或yield
;它创建了一个生成器):但是,对于这个特定的示例,应该使用
any()
或list.count()
(具体取决于接下来要做什么):试试这个
显然
return
语句主要用于将控件返回给调用方函数的函数中 除非在函数中使用它。你宁愿使用打印功能我希望这有帮助
正如@Chris\u Rands所说,你可以使用yield。你知道吗
您应该知道,yield返回的是一个生成器,而不是一个列表。你知道吗
但是,您也可以创建一个包含结果的新列表。你知道吗
相关问题 更多 >
编程相关推荐