python:如果列表中没有以'p ='开头的元素,则返回False

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或者它在第一个元素处出现.

Sco*_*ter 9

这将列出每个元素是否lst满足您的条件,然后计算or这些结果:

any([x.startswith("p=") for x in lst])
Run Code Online (Sandbox Code Playgroud)

  • 为什么列表理解在`any`而不是生成器理解`any(x.startswith("p =")for x in lst)`? (4认同)

Meh*_*dEP 5

使用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)


Soh*_*oqi 5

您可以使用内置方法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)