添加要设置的列表? [英] Add list to set?

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

问题描述

在 Python 2.6 解释器上测试:

<预><代码>>>>a=set('abcde')>>>一种设置(['a','c','b','e','d'])>>>l=['f','g']>>>升['f', 'g']>>>a.添加(l)回溯(最近一次调用最后一次):文件<pyshell#35>",第 1 行,在 <module> 中a.添加(l)类型错误:列表对象不可散列

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

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

解决方案

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

然而你可以向集合中添加元组,因为你不能改变元组的内容:

<预><代码>>>>a.add(('f', 'g'))>>>打印一个设置(['a','c','b','e','d',('f','g')])

<小时>

编辑:一些解释:文档将set定义为一个不同的可散列对象的无序集合.对象必须是可散列的,所以与每次执行这些操作时查看每个单独的元素相比,查找、添加和删除元素可以更快地完成.维基百科文章中解释了所使用的具体算法.Python 哈希算法在 effbot.org 和 python __hash__ 上进行了解释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天全站免登陆