如何在Python中将集合转换为列表?

168 投票
9 回答
427829 浏览
提问于 2025-04-16 20:55

我正在尝试在Python 2.6中把一个集合转换成列表。我使用了这个语法:

first_list = [1,2,3,4]
my_set=set(first_list)
my_list = list(my_set)

但是,我得到了以下的错误信息:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: 'set' object is not callable

我该怎么解决这个问题呢?

9 个回答

10

[编辑] 看起来你之前把“list”这个词重新定义了,使用它作为变量名,就像这样:

list = set([1,2,3,4]) # oops
#...
first_list = [1,2,3,4]
my_set=set(first_list)
my_list = list(my_set)

然后你会得到

Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: 'set' object is not callable
14

不要这样做:

first_list = [1,2,3,4]
my_set=set(first_list)
my_list = list(my_set)

为什么不直接简化这个过程呢:

my_list = list(set([1,2,3,4])

这样做可以帮你去掉列表中的重复项,并返回一个新的列表。

230

这已经是一个列表了:

>>> type(my_set)
<class 'list'>

你想要的是什么样的:

>>> my_set = set([1, 2, 3, 4])
>>> my_list = list(my_set)
>>> print(my_list)
[1, 2, 3, 4]

编辑:

你最后评论的输出:

>>> my_list = [1,2,3,4]
>>> my_set = set(my_list)
>>> my_new_list = list(my_set)
>>> print(my_new_list)
[1, 2, 3, 4]

我在想你是不是做了这样的事情:

>>> set = set()
>>> set([1, 2])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object is not callable

撰写回答