简体   繁体   English

检查任何列表列表中的所有项目是否都在字符串中的最佳方法

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

相关问题 检查字符串中是否有任何列表项 - Check if any list items are in a string 对这两个列表进行缺失项检查的最佳方法是什么 - What is the best way to perform a check against these two lists for missing items Python:检查字符串是否在列表中的任何项目中? - Python: check if string is in any items in a list? 检查列表的所有项目是否都是整数字符串 - Check if all items of a list are string of integers 如何检查列表中的所有项目是否都是字符串 - How to check if all items in list are string Python - 检查字符串是否包含列表中任何项目中的特定字符的最快方法 - Python - Fastest way to check if a string contains specific characters in any of the items in a list 检查 pandas 列是否包含任何列表列表中的所有值 - Check if pandas column contains all values from any list of lists Python - 检查所有列表中是否存在任何项目 - Python - Check if any item exists in all list of lists 将python列表项从字符串转换为数字的最佳方法 - The best way to convert python list items from string to number 有什么简单的方法可以在列表的列表中添加元素,以使列表中的所有列表具有相同数量的元素? - Is there any easy way to add elements in lists in a list to make all lists in a list has a same number of element?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM