如何检查以下所有项目是否都在列表中?

发布于 2024-09-27 13:54:34 字数 621 浏览 6 评论 0原文

我发现有一个相关的问题,关于如何查找列表中是否至少存在一项:
如何检查是否存在以下情况之一项目在列表中?

但是,查找列表中是否所有项目都存在的最佳且Python式的方法是什么?

搜索文档我找到了这个解决方案:

>>> l = ['a', 'b', 'c']
>>> set(['a', 'b']) <= set(l)
True
>>> set(['a', 'x']) <= set(l)
False

其他解决方案是这样的:

>>> l = ['a', 'b', 'c']
>>> all(x in l for x in ['a', 'b'])
True
>>> all(x in l for x in ['a', 'x'])
False

但是在这里你必须做更多的打字。

还有其他解决方案吗?

I found, that there is related question, about how to find if at least one item exists in a list:
How to check if one of the following items is in a list?

But what is the best and pythonic way to find whether all items exists in a list?

Searching through the docs I found this solution:

>>> l = ['a', 'b', 'c']
>>> set(['a', 'b']) <= set(l)
True
>>> set(['a', 'x']) <= set(l)
False

Other solution would be this:

>>> l = ['a', 'b', 'c']
>>> all(x in l for x in ['a', 'b'])
True
>>> all(x in l for x in ['a', 'x'])
False

But here you must do more typing.

Is there any other solutions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

一桥轻雨一伞开 2024-10-04 13:54:34

Python 中的 <= 等运算符通常不会被重写为与“小于或等于”显着不同的含义。标准库这样做很不寻常——对我来说,它就像遗留的 API。

使用等效且命名更清晰的方法 set.issubset。请注意,您不需要将参数转换为集合;如果需要的话它会为你做到这一点。

set(['a', 'b']).issubset(['a', 'b', 'c'])

Operators like <= in Python are generally not overriden to mean something significantly different than "less than or equal to". It's unusual for the standard library does this--it smells like legacy API to me.

Use the equivalent and more clearly-named method, set.issubset. Note that you don't need to convert the argument to a set; it'll do that for you if needed.

set(['a', 'b']).issubset(['a', 'b', 'c'])
作死小能手 2024-10-04 13:54:34

我可能会在下面使用 set方式:

set(l).issuperset(set(['a','b'])) 

或者反过来:

set(['a','b']).issubset(set(l)) 

我发现它更具可读性,但它可能有点过头了。集合对于计算集合之间的并集/交集/差异特别有用,但在这种情况下它可能不是最佳选择......

I would probably use set in the following manner :

set(l).issuperset(set(['a','b'])) 

or the other way round :

set(['a','b']).issubset(set(l)) 

I find it a bit more readable, but it may be over-kill. Sets are particularly useful to compute union/intersection/differences between collections, but it may not be the best option in this situation ...

清醇 2024-10-04 13:54:34

我喜欢这两个,因为它们看起来最合乎逻辑,后者更短并且可能最快(此处使用 set 文字语法显示,该语法已 向后移植 到 Python 2.7):

all(x in {'a', 'b', 'c'} for x in ['a', 'b'])
#   or
{'a', 'b'}.issubset({'a', 'b', 'c'})

I like these two because they seem the most logical, the latter being shorter and probably fastest (shown here using set literal syntax which has been backported to Python 2.7):

all(x in {'a', 'b', 'c'} for x in ['a', 'b'])
#   or
{'a', 'b'}.issubset({'a', 'b', 'c'})
早乙女 2024-10-04 13:54:34

如果您的列表包含像这样的重复项怎么办:

v1 = ['s', 'h', 'e', 'e', 'p']
v2 = ['s', 's', 'h']

集合不包含重复项。因此,以下行返回 True。

set(v2).issubset(v1)

要计算重复项,您可以使用以下代码:

v1 = sorted(v1)
v2 = sorted(v2)


def is_subseq(v2, v1):
    """Check whether v2 is a subsequence of v1."""
    it = iter(v1)
    return all(c in it for c in v2) 

因此,以下行返回 False。

is_subseq(v2, v1)

What if your lists contain duplicates like this:

v1 = ['s', 'h', 'e', 'e', 'p']
v2 = ['s', 's', 'h']

Sets do not contain duplicates. So, the following line returns True.

set(v2).issubset(v1)

To count for duplicates, you can use the code:

v1 = sorted(v1)
v2 = sorted(v2)


def is_subseq(v2, v1):
    """Check whether v2 is a subsequence of v1."""
    it = iter(v1)
    return all(c in it for c in v2) 

So, the following line returns False.

is_subseq(v2, v1)
执笏见 2024-10-04 13:54:34

不是OP的情况,但是 - 对于任何想要在 dicts 中断言交集并由于谷歌搜索不佳而最终到达这里的人(例如我) - 你需要使用 dict.items

>>> a = {'key': 'value'}
>>> b = {'key': 'value', 'extra_key': 'extra_value'}
>>> all(item in a.items() for item in b.items())
True
>>> all(item in b.items() for item in a.items())
False

这是因为 dict.items 返回键/值对的元组,并且很像 Python 中的任何对象,它们可以互换比较

Not OP's case, but - for anyone who wants to assert intersection in dicts and ended up here due to poor googling (e.g. me) - you need to work with dict.items:

>>> a = {'key': 'value'}
>>> b = {'key': 'value', 'extra_key': 'extra_value'}
>>> all(item in a.items() for item in b.items())
True
>>> all(item in b.items() for item in a.items())
False

That's because dict.items returns tuples of key/value pairs, and much like any object in Python, they're interchangeably comparable

邮友 2024-10-04 13:54:34

另一种解决方案是:

l = ['a', 'b', 'c']
potential_subset1 = ['a', 'b']
potential_subset2 = ['a', 'x']
print(False not in [i in l for i in potential_subset1]) # True
print(False not in [i in l for i in potential_subset2]) # False

我的解决方案之所以出色,是因为您可以通过将列表内联来编写单行代码。

Another solution would be:

l = ['a', 'b', 'c']
potential_subset1 = ['a', 'b']
potential_subset2 = ['a', 'x']
print(False not in [i in l for i in potential_subset1]) # True
print(False not in [i in l for i in potential_subset2]) # False

What makes my solution great is that you can write one-liners by putting the lists inline.

昵称有卵用 2024-10-04 13:54:34

如何使用 lambda 表达式执行此操作的示例如下:

issublist = lambda x, y: 0 in [_ in x for _ in y]

An example of how to do this using a lambda expression would be:

issublist = lambda x, y: 0 in [_ in x for _ in y]
你げ笑在眉眼 2024-10-04 13:54:34

简短的语法

我在尝试 Python 解释器时发现了一种非常可读的语法。

>>> my_list = [1, 2, 3, 4, 5]
>>> (6 or 7) in my_list
False
>>> (2 or 6) in my_list
True
>>> (2 and 6) in my_list
False
>>> (2 and 5) in my_list
True

要搜索的项目列表

如果您有一长串要搜索的对象,保存在 sub_list 变量中:

>>> my_list = [1, 2, 3, 4, 5]
>>> sub_list = ['x', 'y']

如果超集中包含任何(至少一个)项目(或< /code> 语句):

>>> next((True for item in sub_list if next((True for x in my_list if x == item), False)), False)
False

>>> sub_list[0] = 3
>>> next((True for item in sub_list if next((True for x in my_list if x == item), False)), False)
True

如果所有项都包含在超集(and 语句)中,则 sub_list 是完整子集。还具有一些德摩根定律

>>> next((False for item in sub_list if item not in my_list), True)
False

>>> sub_list[1] = 2
>>> next((False for item in sub_list if item not in my_list), True)
True
>>> next((True for item in sub_list if next((True for x in my_list if x == item), False)), False)
True

Short syntax

I discovered a very readable syntax while experimenting on the Python interpreter.

>>> my_list = [1, 2, 3, 4, 5]
>>> (6 or 7) in my_list
False
>>> (2 or 6) in my_list
True
>>> (2 and 6) in my_list
False
>>> (2 and 5) in my_list
True

List of items to search for

If you have a long list of objects to search for, held in a sub_list variable:

>>> my_list = [1, 2, 3, 4, 5]
>>> sub_list = ['x', 'y']

If any (at least one) item is contained in the superset (or statement):

>>> next((True for item in sub_list if next((True for x in my_list if x == item), False)), False)
False

>>> sub_list[0] = 3
>>> next((True for item in sub_list if next((True for x in my_list if x == item), False)), False)
True

If all items are contained in superset (and statement), then sub_list is a full subset. Also featuring a bit of De Morgan's Law:

>>> next((False for item in sub_list if item not in my_list), True)
False

>>> sub_list[1] = 2
>>> next((False for item in sub_list if item not in my_list), True)
True
>>> next((True for item in sub_list if next((True for x in my_list if x == item), False)), False)
True
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文