Python: Add list to set?

2019-01-07 02:22发布

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.

标签: python list set
12条回答
老娘就宠你
2楼-- · 2019-01-07 02:58
>>> a = set('abcde')
>>> l = ['f', 'g']
>>> a |= set(l)
>>> a
set(['a', 'c', 'b', 'e', 'd', 'g', 'f'])

The union operator is much faster than add anyway.

edit: If you want the list itself and not its members, then you must use a tuple, unfortunately. Set members must be hashable.

查看更多
太酷不给撩
3楼-- · 2019-01-07 03:00

Sets can't have mutable (changeable) elements/members. A list, being mutable, cannot be a member of a set.

As sets are mutable, you cannot have a set of sets! You can have a set of frozensets though.

(The same kind of "mutability requirement" applies to the keys of a dict.)

Other answers have already given you code, I hope this gives a bit of insight. I'm hoping Alex Martelli will answer with even more details.

查看更多
Lonely孤独者°
4楼-- · 2019-01-07 03:07

list objects are unhashable. you might want to turn them in to tuples though.

查看更多
小情绪 Triste *
5楼-- · 2019-01-07 03:08

You want to add a tuple, not a list:

>>> a=set('abcde')
>>> a
set(['a', 'c', 'b', 'e', 'd'])
>>> l=['f','g']
>>> l
['f', 'g']
>>> t = tuple(l)
>>> t
('f', 'g')
>>> a.add(t)
>>> a
set(['a', 'c', 'b', 'e', 'd', ('f', 'g')])

If you have a list, you can convert to the tuple, as shown above. A tuple is immutable, so it can be added to the set.

查看更多
Lonely孤独者°
6楼-- · 2019-01-07 03:10

Please notice the function set.update(). The documentation says:

Update a set with the union of itself and others.

查看更多
来,给爷笑一个
7楼-- · 2019-01-07 03:10

You'll want to use tuples, which are hashable (you can't hash a mutable object like a list).

>>> a = set("abcde")
>>> a
set(['a', 'c', 'b', 'e', 'd'])
>>> t = ('f', 'g')
>>> a.add(t)
>>> a
set(['a', 'c', 'b', 'e', 'd', ('f', 'g')])
查看更多
登录 后发表回答