Python未全部运行

发布于 2024-08-17 16:00:22 字数 163 浏览 1 评论 0原文

如何检查列表是否是更大列表的子集。

a = [1,2,3]b = [1,2,3,4,5,6] 的子集

我可以做类似的事情吗

if a all in b

How do I check if a list is a subset of a bigger list.

i.e.

a = [1,2,3] is a subset of b = [1,2,3,4,5,6]

Can I do something like

if a all in b

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

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

发布评论

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

评论(3

╰ゝ天使的微笑 2024-08-24 16:00:22
>>> a = set([1, 2, 3])
>>> b = set([1, 2, 3, 4, 5, 6])
>>> a.issubset(b)
True

>>> a = [1, 2, 3]
>>> b = [1, 2, 3, 4, 5, 6]
>>> all(map(lambda x: x in b, a))
True
>>> a = [1, 2, 3, 9]
>>> all(map(lambda x: x in b, a))
False

或(如果元素数量很重要)

>>> a = [1, 1, 2, 3]
>>> all(map(lambda x: a.count(x) <= b.count(x), a))
False
>>> a = set([1, 2, 3])
>>> b = set([1, 2, 3, 4, 5, 6])
>>> a.issubset(b)
True

or

>>> a = [1, 2, 3]
>>> b = [1, 2, 3, 4, 5, 6]
>>> all(map(lambda x: x in b, a))
True
>>> a = [1, 2, 3, 9]
>>> all(map(lambda x: x in b, a))
False

or (if the number of elements is important)

>>> a = [1, 1, 2, 3]
>>> all(map(lambda x: a.count(x) <= b.count(x), a))
False
記憶穿過時間隧道 2024-08-24 16:00:22

主要喜欢其他答案,但我确实更喜欢这里的生成器语法,看起来更自然,并且它是惰性评估的:

if all(x in b for x in a):
    pass

如果您关心重复元素的数量,这个选项看起来不错,您可以优化它对 c 进行排序并使用二等分:

def all_in(a, b)
    try:
        c = b[:]
        for x in a: c.remove[x]
        return True
    except:
        return False

mostly like the other answers, but I do prefer the generator syntax here, seems more natural and it's lazily evaluated:

if all(x in b for x in a):
    pass

if you care about the number of repeated elements, this option seems nice, and you could optimize it sorting c and using bisect:

def all_in(a, b)
    try:
        c = b[:]
        for x in a: c.remove[x]
        return True
    except:
        return False
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文