使用Python作为一组中的项目 [英] Use dicts as items in a set in Python

查看:182
本文介绍了使用Python作为一组中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

Came across a few solutions on here that involved a bunch of stuff that looked really complex and error-prone (seemed to be problems with iterating over the dict in undefined orders, etc...). Would be nice to do something like this which is technically not mathematically valid because two objects can have different information, but be evaluated as equal, but works great for plenty of real life use cases:

# 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)


推荐答案

不,你不行。你只能将不可变值放入一个集合中。这个限制不仅仅是能够比较价值观;您需要测试两者是否相等,并且能够获取哈希值,并且最重要的是具有以保持稳定。可变值不符合上一个要求。

No, you cannot. You can only put immutable values into a set. This restriction has to do with more than just being able to compare values; you need to test both for equality and be able to obtain a hash value, and most of all the value has to remain stable. Mutable values fail that last requirement.

通过将字典转换成一系列键值元组,可以使字典变得不可变;如果值是不可变的,以下工作如下:

A dictionary can be made immutable by turning it into a series of key-value tuples; provided the values are immutable too, the following works:

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

这样可以测试至少在widget_set 中测试 tuple(sorted(somedict.items()))存在相同的字典。将值转回 dict 是一个调用 dict 的问题:

This makes it possible to test for the presence of the same dictionary by testing for tuple(sorted(somedict.items())) in widget_set at least. Turning the values back into a dict is a question of calling dict on it:

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'}

这篇关于使用Python作为一组中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆