简体   繁体   English

蟒蛇3。 如何检查后缀是否在列表中的某些单词中?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM