[英]Python3. How to check if a suffix is in some of the words in a list?
I am using python3 and coming across this question.我正在使用 python3 并遇到这个问题。 Say I have a list
说我有一个清单
L = ["money", "fame", "popularity"]
I want to check if there is any word in L
that contains "pop"
.我想检查
L
中是否有包含"pop"
单词。 I know that if L
is a string, eg if L = "I want to be popular"
, then I can just do "pop" in l
, and the boolean value will be returned.我知道如果
L
是一个字符串,例如如果L = "I want to be popular"
,那么我可以"pop" in l
执行"pop" in l
,并且将返回布尔值。 But now L
is a list, how can I check if any word in this list contains "pop"
then?但是现在
L
是一个列表,我如何检查这个列表中是否有任何单词包含"pop"
呢? (not using a loop if possible) (如果可能,不使用循环)
Use any()
to return a True
for any match case:使用
any()
为任何匹配案例返回True
:
any('pop' in x for x in L)
Code :代码:
L = ["money", "fame", "popularity"]
print(any('pop' in x for x in L))
# True
You can use filter with lambda function您可以将过滤器与 lambda 函数一起使用
L = ["populate", "position", "popcorn"]
didContainPop = len(list(filter(lambda x: "pop" in x, L))) != 0
print(didContainPop)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.