使用{}从列表创建集合 [英] Create a set from a list using {}
问题描述
有时候我有一个列表,我想用它做一些设定的动作.我要做的是写这样的东西:
Sometimes I have a list and I want to do some set actions with it. What I do is to write things like:
>>> mylist = [1,2,3]
>>> myset = set(mylist)
{1, 2, 3}
今天我发现从Python 2.7中,您还可以通过直接说{1,2,3}
来定义集合,这似乎是定义它的等效方法.
Today I discovered that from Python 2.7 you can also define a set by directly saying {1,2,3}
, and it appears to be an equivalent way to define it.
然后,我想知道是否可以使用此语法从给定列表中创建一个集合.
Then, I wondered if I can use this syntax to create a set from a given list.
{list}
失败,因为它试图创建仅包含一个元素(列表)的集合.而且列表是不可散列的.
{list}
fails because it tries to create a set with just one element, the list. And lists are unhashable.
>>> mylist = [1,2,3]
>>> {mylist}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
所以,我想知道:是否可以使用{}
语法而不是set()
从列表中创建集合?
So, I wonder: is there any way to create a set out of a list using the {}
syntax instead of set()
?
推荐答案
I asked a related question recently: Python Set: why is my_set = {*my_list} invalid?. My question contains your answer if you are using Python 3.5
>>> my_list = [1,2,3,4,5]
>>> my_set = {*my_list}
>>> my_set
{1, 2, 3, 4, 5}
它在Python 2上不起作用(这是我的问题)
It won't work on Python 2 (that was my question)
这篇关于使用{}从列表创建集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!