添加列表进行设置? [英] Add list to set?

查看:54
本文介绍了添加列表进行设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 2.6解释器上测试:

>>> a=set('abcde')
>>> a
set(['a', 'c', 'b', 'e', 'd'])
>>> l=['f','g']
>>> l
['f', 'g']
>>> a.add(l)
Traceback (most recent call last):
  File "<pyshell#35>", line 1, in <module>
    a.add(l)
TypeError: list objects are unhashable

我认为我无法将列表添加到集合中,因为Python无法告诉我是否两次添加了相同的列表.有解决方法吗?

我想添加列表本身,而不是其元素.

解决方案

您不能将列表添加到集合中,因为列表是可变的,这意味着您可以在将列表添加到集合后更改列表的内容. /p>

但是您可以将元组添加到集合中,因为您不能更改元组的内容:

>>> a.add(('f', 'g'))
>>> print a
set(['a', 'c', 'b', 'e', 'd', ('f', 'g')])


编辑:某些解释:文档将set定义为不同的可哈希对象的无序集合.这些对象必须是可哈希的,以便查找,添加和添加对象.与每次执行这些操作时查看每个单独的元素相比,删除元素的完成速度更快. Wikipedia文章中对使用的特定算法进行了说明. Python的哈希算法在 effbot.org Python参考.

一些事实:

  • 设置元素以及字典键必须是可哈希的
  • 一些不可散列的数据类型:
    • list:改为使用tuple
    • set:改用frozenset
    • dict:没有官方对应文件,但是有一些 食谱
  • 对象实例默认情况下是可哈希的,每个实例都有唯一的哈希.您可以按照python参考中的说明覆盖此行为.

Tested on Python 2.6 interpreter:

>>> a=set('abcde')
>>> a
set(['a', 'c', 'b', 'e', 'd'])
>>> l=['f','g']
>>> l
['f', 'g']
>>> a.add(l)
Traceback (most recent call last):
  File "<pyshell#35>", line 1, in <module>
    a.add(l)
TypeError: list objects are unhashable

I think that I can't add the list to the set because there's no way Python can tell If I have added the same list twice. Is there a workaround?

EDIT: I want to add the list itself, not its elements.

解决方案

You can't add a list to a set because lists are mutable, meaning that you can change the contents of the list after adding it to the set.

You can however add tuples to the set, because you cannot change the contents of a tuple:

>>> a.add(('f', 'g'))
>>> print a
set(['a', 'c', 'b', 'e', 'd', ('f', 'g')])


Edit: some explanation: The documentation defines a set as an unordered collection of distinct hashable objects. The objects have to be hashable so that finding, adding and removing elements can be done faster than looking at each individual element every time you perform these operations. The specific algorithms used are explained in the Wikipedia article. Pythons hashing algorithms are explained on effbot.org and pythons __hash__ function in the python reference.

Some facts:

  • Set elements as well as dictionary keys have to be hashable
  • Some unhashable datatypes:
    • list: use tuple instead
    • set: use frozenset instead
    • dict: has no official counterpart, but there are some recipes
  • Object instances are hashable by default with each instance having a unique hash. You can override this behavior as explained in the python reference.

这篇关于添加列表进行设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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