[英]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 如果两者( foobarbaz
和terms
)都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.