python:如果列表中没有以';p=';
有一张这样的清单python:如果列表中没有以';p=';,python,list,loops,any,Python,List,Loops,Any,有一张这样的清单 lst = ['hello', 'stack', 'overflow', 'friends'] 我怎样才能做到: if there is not an element in lst starting with 'p=' return False else return True for i in lst: if i.startswith('p=') return True ? 我的想法是: if there is not an element in l
lst = ['hello', 'stack', 'overflow', 'friends']
我怎样才能做到:
if there is not an element in lst starting with 'p=' return False else return True
for i in lst:
if i.startswith('p=')
return True
?
我的想法是:
if there is not an element in lst starting with 'p=' return False else return True
for i in lst:
if i.startswith('p=')
return True
但是我不能在循环中添加return False,也不能在第一个元素中添加return False。好吧,让我们分两部分来做: 首先,您可以创建一个新列表,其中每个元素都是一个字符串,只包含每个原始项的前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))
这将测试
lst
的每个元素是否满足您的条件,然后计算这些结果的或
:
any(x.startswith("p=") for x in lst)
试试这个
if len([e for e in lst if e.startwith("p=")])==0: return False
使用
any
条件检查具有相同条件的列表中的所有元素:
lst = ['hello','p=15' ,'stack', 'overflow', 'friends']
return any(l.startswith("p=") for l in lst)
我建议使用迭代器,例如
output = next((True for x in lst if x.startswith('p=')),False)
这将为以
'p='开头的第一个lst
元素输出True
,然后停止搜索。如果到达末尾时未找到'p='
,则返回False
您可以使用内置方法检查它,列表中的任何元素都以p=
开头。使用string的方法检查string的开头
>>> 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
@ScottHunter Sure因为您只知道它是False
一旦您测试了所有元素,您应该在循环完成后返回False
。然后将return False
放在循环之外,或者放在else
块中。你不可能确定到底有没有。或者只使用返回any(…)
。为什么在any中使用列表理解而不是生成器理解any(x.startswith(“p=”)表示lst中的x)
?我删除了列表理解。你在浪费内存和测试。使用生成器表达式any()
可以使回路短路;当第一个元素通过测试时,无需再测试后面的所有内容。在列表(map(lambda x:x[:2],lst))中返回'p=”
这是无效的python语法。除非你把它放在一个盒子里function@GarbageCollector我认为OP真的意味着代码在函数中,从措辞和示例postedYes判断,我想是的。最好在答案中写完整的函数,以避免任何歧义。