python 将集合转换为列表时无法调用列表对象

python list object not callable when transforming set to list

a=[1,2,3]
b=[2,4,5,6]

c=set(a).intersection(b)  #output is set([2])

如何只输出 2?

我试过 list(c) 但遇到了这个错误:

TypeError: 'list' object is not callable
>>> a=[1,2,3]
>>> b=[2,4,5,6]
>>> c=set(a).intersection(b) 
>>> print c
set([2])
>>> print type(c)
<type 'set'>
>>> elem = c.pop()
>>> print elem
2

输出为set很正常,毕竟交集的结果可以产生多个元素。如果您对 list 元素感兴趣,这对我有用:

c = set(a).intersection(b)
list(c)
=> [2]

你收到错误 'list' object is not callable 很奇怪,这不应该发生。也许你在某处重新定义了 list?查看你的代码,看看你是否做了这样的事情:

list = [1, 2, 3]

...这就是为什么重新定义 built-in 函数不是一个好主意。