【问题标题】:Use dicts as items in a set in Python在 Python 中使用 dicts 作为集合中的项目
【发布时间】:2013-05-08 00:54:16
【问题描述】:

有没有办法通过使用简单的方法(如比较器函数)将一些 dict 对象放入 Python 中的集合中?

在这里遇到了一些解决方案,其中涉及一堆看起来非常复杂且容易出错的东西(似乎是在未定义的顺序中迭代 dict 时出现问题,等等......)。做这样的事情会很好,这在技术上在数学上是无效的,因为两个对象可以具有不同的信息,但被评估为相等,但适用于大量现实生活用例:

# One of the dicts:
widget = {
     lunch:  'eggs',
     dunner: 'steak'
}

# Define a comparator function (ignores dinner)
def comparator(widget1, widget2):
     return widget1['lunch'] > widget2['lunch']

widget_set = set([widget], comparator)

【问题讨论】:

    标签: python dictionary set


    【解决方案1】:

    不,你不能。您只能将不可变值放入集合中。此限制不仅仅与能够比较值有关;您需要测试两者是否相等并能够获得哈希值,并且大多数值 必须 保持稳定。可变值不符合最后一个要求。

    可以通过将字典转换为一系列键值元组来使字典不可变;如果这些值也是不可变的,则以下工作:

    widget_set = {tuple(sorted(widget.items()))}  # {..} is a set literal, Python 2.7 and newer
    

    这使得通过至少测试tuple(sorted(somedict.items())) in widget_set 来测试是否存在同一个字典成为可能。将值转回dict 是一个调用dict 的问题:

    dict(widget_set.pop())
    

    演示:

    >>> widget = {
    ...      'lunch':  'eggs',
    ...      'dunner': 'steak'
    ... }
    >>> widget_set = {tuple(sorted(widget.items()))}
    >>> tuple(sorted(widget.items())) in widget_set
    True
    >>> dict(widget_set.pop())
    {'lunch': 'eggs', 'dunner': 'steak'}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-12
      • 2017-03-06
      • 2019-09-20
      • 1970-01-01
      • 2019-08-28
      • 1970-01-01
      • 1970-01-01
      • 2014-05-31
      相关资源
      最近更新 更多