简体   繁体   English

查找Python中的另一个列表中是否存在任何列表元素

[英]Find if any element of list exists in another list in Python

The question is about a quicker, ie. 问题是关于更快,即。 more pythonic, way to test if any of the elements in an iterable exists inside another iterable. 更多pythonic,测试迭代中的任何元素是否存在于另一个iterable中的方法。

What I am trying to do is something like: 我想要做的是:

if "foo" in terms or "bar" in terms or "baz" in terms: pass

But apparently this way repeats the 'in terms' clause and bloats the code, especially when we are dealing with many more elements. 但显然这种方式重复了'in terms'子句并使代码膨胀,特别是当我们处理更多元素时。 So I wondered whether is a better way to do this in python. 所以我想知道在python中是否有更好的方法。

You could also consider in your special case if it is possible to use set s instead of iterables. 在特殊情况下,您还可以考虑是否可以使用set而不是iterables。 If both ( foobarbaz and terms ) are set s, then you can just write 如果两者( foobarbazterms )都set ,那么你可以写

if foobarbaz & terms:
    pass

This isn't particularly faster than your way, but it is smaller code by far and thus probably better for reading. 这并不比你的方式特别快,但到目前为止它是更小的代码,因此可能更适合阅读。

And of course, not all iterables can be converted to set s, so it depends on your usecase. 当然,并非所有迭代都可以转换为set ,因此它取决于您的用例。

Figured out a way, posting here for easy reference. 想出办法,在这里张贴以便于参考。 Try this: 尝试这个:

if any(term in terms for term in ("foo", "bar", "baz")): pass

Faster than Alfe's answer, since it only tests for, rather than calculates the, intersection 比Alfe的答案更快,因为它只测试,而不是计算交叉点

if not set(terms).isdisjoint({'foo', 'bar', 'baz'}):
    pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 查找列表中的任何元素是否在另一个列表中 - find if any element of list is in another list 查找列表的元素是否存在于另一个字符串中 - Find whether an element of a list exists in another string 如果存在于另一个列表中,python从嵌套列表中删除该元素+ - python remove element from nested list if it exists in another list + 如果一个列表中的元素存在于 Python 中的另一个列表中,如何打印该元素? - How to print an element from one list if it exists in another list in Python? python查找字符串列表的每个元素是否包含另一个字符串列表中的任何一个 - python find if each element of a string list contains any of another string list 如何检查列表中的元素是否存在于另一个列表中 - How to check if an element in the list exists in another list Python:如何确定列表中是否存在未知元素? - Python: How to find out if an unknown element exists in a list? 在Python中的另一个列表中查找一个列表中任何项目的最后一次出现 - Find last occurrence of any item of one list in another list in python Python:查找另一个列表中包含次数最少的列表元素 - Python: Find the list element that is contained least times in another list Python - 从作为另一个元素的子字符串的字符串列表中删除任何元素 - Python - Remove any element from a list of strings that is a substring of another element
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM