Create a set from a list using {}

久未见 提交于 2019-12-11 00:39:56

问题


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}

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

So, I wonder: is there any way to create a set out of a list using the {} syntax instead of set()?


回答1:


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}

It won't work on Python 2 (that was my question)




回答2:


Basically they are not equivalent (expression vs function). The main purpose of adding {} to python was because of set comprehension (like list comprehension) which you can also create a set using it by passing some hashable objects.

So if you want to create a set using {} from an iterable you can use a set comprehension like following:

{item for item in iterable}

Also note that empty braces represent a dictionary in python not a set. So if you want to just create an empty set the proper way is using set() function.




回答3:


You can use

>>> ls = [1,2,3]
>>> {i for i in ls}
{1,2,3}


来源:https://stackoverflow.com/questions/36198829/create-a-set-from-a-list-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!