[英]Best way to check if all of the items in any of a list of lists are in a string
I have a list of lists like mylist = [["1", "2"], ["abc", "def"]]
and a string like mystr = "1 2"
.我有一个像
mylist = [["1", "2"], ["abc", "def"]]
这样的mystr = "1 2"
和一个像mystr = "1 2"
这样的字符串。
I want to check if any of the lists in mylist
have all of their strings in the string.我想检查
mylist
任何列表是否在字符串中包含所有字符串。
I have achieved this by doing the following.我通过执行以下操作实现了这一点。
if True in [all(keyword in mystr for keyword in keywords) for keywords in mylist]:
print("yes")
Is there a faster way?有没有更快的方法?
Yes, using any
.是的,使用
any
.
if any(all(keyword in mystr for keyword in keywords) for keywords in mylist):
print("yes")
This is faster because it stops iterating (short-circuits) as soon as it sees a true value.这更快,因为它一旦看到真值就停止迭代(短路)。 It also has a side-benefit of being easier to read.
它还具有更易于阅读的附带好处。
Thanks to jonrsharpe for mentioning this in the comments感谢jonrsharpe 在评论中提到这一点
matcher = mystr.__contains__
any(all(map(matcher, keywords)) for keywords in mylist)
Benchmarks:基准:
>>> min(repeat(lambda: any(all(map(matcher, keywords)) for keywords in mylist), repeat=20))
1.1285329000002093
>>> min(repeat(lambda: any(all(map(mystr.__contains__, keywords)) for keywords in mylist), repeat=20))
1.2246240000004036
>>> min(repeat(lambda: any(all(keyword in mystr for keyword in keywords) for keywords in mylist), repeat=20))
1.3369910999999775
>>> min(repeat(lambda: True in [all(keyword in mystr for keyword in keywords) for keywords in mylist], repeat=20))
1.726889200000187
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.