91D*_*Dev 4 python loops list any
有一个像这样的清单
lst = ['hello', 'stack', 'overflow', 'friends']
Run Code Online (Sandbox Code Playgroud)
我该怎么做:
if there is not an element in lst starting with 'p=' return False else return True
Run Code Online (Sandbox Code Playgroud)
?
我在想的是:
for i in lst:
if i.startswith('p=')
return True
Run Code Online (Sandbox Code Playgroud)
但是我不能在循环中添加返回False或者它在第一个元素处出现.
这将列出每个元素是否lst满足您的条件,然后计算or这些结果:
any([x.startswith("p=") for x in lst])
Run Code Online (Sandbox Code Playgroud)
使用if/any条件检查列表中具有相同条件的所有元素:
lst = ['hello','p=15' ,'stack', 'overflow', 'friends']
if any(l.startswith("p=") for l in lst):
return False
return True
Run Code Online (Sandbox Code Playgroud)
您可以使用内置方法any来检查列表中以 开头的任何元素p=。使用字符串的startswith方法来检查字符串的开头
>>> lst = ['hello', 'stack', 'overflow', 'friends']
>>> any(map(lambda x: x.startswith('p='),lst))
>>> False
Run Code Online (Sandbox Code Playgroud)
一个应该导致的例子 True
>>> lst = ['hello', 'p=stack', 'overflow', 'friends']
>>> any(map(lambda x: x.startswith('p='),lst))
>>> True
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
252 次 |
| 最近记录: |