Python: return False if there is no element in the list starting with 'p ='

having a list e.g.

lst = ['hello', 'stack', 'overflow', 'friends']

how can i do something like:

if there is not an element in lst starting with 'p=' return False else return True

?

I thought something like:

for i in lst:
   if i.startswith('p=')
       return True

but I cannot add a False return inside the loop or it exits in the first element.

+4
source share
6 answers

This will cause each element to lstsatisfy your condition and then calculate orthese results:

any([x.startswith("p=") for x in lst])
+9
source

use if/anyconditions to check all items in the list with the same condition:

lst = ['hello','p=15' ,'stack', 'overflow', 'friends']
if any(l.startswith("p=") for l in lst):
    return False
return True
+5
source

any, , p=. string startswith,

>>> lst = ['hello', 'stack', 'overflow', 'friends']
>>> any(map(lambda x: x.startswith('p='),lst))
>>> False

, True

>>> lst = ['hello', 'p=stack', 'overflow', 'friends']
>>> any(map(lambda x: x.startswith('p='),lst))
>>> True
+4

,

output = next((True for x in lst if x.startswith('p=')),False)

True lst, 'p=', . , 'p=', False.

+3

, :

, , , 3 . map() :

newlist = list(map(lambda x: x[:2], lst))

, "p=" . :    "p ="

:

def any_elem_starts_with_p_equals(lst):
    return 'p=' in list(map(lambda x: x[:2], lst))
+2

if len([e for e in lst if e.startwith("p=")])==0: return False
+2

Source: https://habr.com/ru/post/1692459/


All Articles