简化 Python 中的表达式
我觉得必须有一种更简单/更干净/更快(选择一个或多个)的方法来编写这个表达式......
采用 BigString =“这是一个关于一只名叫花花公子的红猫的长句子。”
和 LittleStringList = [ "red dog", "red cat", "red mouse" ]
我实际上想要一个当 LittleStringList 之一位于 BigString 中时返回 true 的函数/表达式。我是这样写的:
def listcontains(list, big):
contains = False
for string in list:
if string in big:
contains = True
else:
pass
return contains
感谢任何帮助!谢谢。
编辑:修正了一个小错误!
I feel there must be a simpler/cleaner/faster (choose one or more) way to write this expression...
take a BigString = "This is a long sentence about a red cat named dude."
and LittleStringList = [ "red dog", "red cat", "red mouse" ]
I effectively want a function/expression that returns true when one of LittleStringList is in BigString. I wrote it like this:
def listcontains(list, big):
contains = False
for string in list:
if string in big:
contains = True
else:
pass
return contains
Any help is appreciated! Thanks.
edit: Fixed a small error!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
any([BigString 中的 s for LittleStringList 中的 s])
或者使用生成器表达式更好 - 正如 @GWW 所指出的:
any(BigString 中的 s for LittleStringList 中的 s)
>any([s in BigString for s in LittleStringList])
or even better using a generator expression - as pointed out by @GWW:
any(s in BigString for s in LittleStringList)
使用任何():
use any():
我假设你的意思是
if string in big
?也许然后尝试:
或者带有生成器的版本:
I assume you mean
if string in big
?Maybe then try:
Or a version with a generator:
string
作为变量名,它是一个模块,str
是一种类型,更好的词会是单词
。list
作为变量名list
并再次检查list
,而不是 bigso
string
as variable name, it is a module,str
is a type, better word would beword
.list
as variable namelist
and checking again inlist
, instead of bigso
为了缩短它,你可以写:
To shorten it a little you could instead write:
any(filter(lambda x: x in BigString, LittleStringList))
过滤器将返回 BigString 中包含 LittleStringList 单词的列表,如果过滤器返回出现某种情况的列表,则 any 将返回 true
any(filter(lambda x: x in BigString, LittleStringList))
filter will return a list with LittleStringList words inside BigString and any will return true if filter returns a list with some occurence