【问题标题】:Find set with smallest number of elements from a list of sets [duplicate]从集合列表中查找元素数量最少的集合[重复]
【发布时间】:2019-04-15 19:54:30
【问题描述】:

我有一个集合列表 -

inconsistent_case = [{0, 1, 2, 3, 6, 7}, {4, 5}]

我想要-

{4, 5}(用最少的元素设置)

我的代码 -

length = float("inf")
small = {}
for x in inconsistent_case:
    if len(x) < length:
        length = len(x)
        small = x
print(small)

这给了我 -

{4, 5}

有没有最快和/或最简单的方法来做到这一点?

【问题讨论】:

  • 感谢@Patrick Haugh,将其标记为重复。

标签: python-3.x nested


【解决方案1】:

是的,指定min的密钥:

>>> inconsistent_case = [{0, 1, 2, 3, 6, 7}, {4, 5}]
>>> min(inconsistent_case, key=len)
{4, 5}

如果多个项目最少,则该函数返回遇到的第一个。

【讨论】:

  • 感谢@wim,它工作得很好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-07-05
  • 1970-01-01
  • 1970-01-01
  • 2020-04-12
  • 1970-01-01
  • 2022-12-08
  • 2011-09-23
相关资源
最近更新 更多