Python设置为列表
如何在Python中将集合转换为列表?使用Python设置为列表,python,list,set,Python,List,Set,如何在Python中将集合转换为列表?使用 a = set(["Blah", "Hello"]) a = list(a) 不起作用。它给了我: TypeError: 'set' object is not callable 您的代码确实有效(使用cpython 2.4、2.5、2.6、2.7、3.1和3.2进行了测试): 检查您是否无意中覆盖了列表: >>> assert list == __builtins__.list 您的代码在Win7 x64上使用Python 3
a = set(["Blah", "Hello"])
a = list(a)
不起作用。它给了我:
TypeError: 'set' object is not callable
您的代码确实有效(使用cpython 2.4、2.5、2.6、2.7、3.1和3.2进行了测试):
检查您是否无意中覆盖了列表
:
>>> assert list == __builtins__.list
您的代码在Win7 x64上使用Python 3.2.1
a = set(["Blah", "Hello"])
a = list(a)
type(a)
<class 'list'>
a=set([“废话”,“你好])
a=列表(a)
类型(a)
由于意外地将内置集用作变量名,因此隐藏了内置集,下面是一种复制错误的简单方法
>>> set=set()
>>> set=set()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'set' object is not callable
>>set=set()
>>>set=set()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:“set”对象不可调用
第一行将集合重新绑定到集合的实例。第二行尝试调用实例,当然失败了
下面是一个不太容易混淆的版本,每个变量使用不同的名称。使用新的解释器
>>> a=set()
>>> b=a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'set' object is not callable
>a=set()
>>>b=a()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:“set”对象不可调用
希望调用
a
显然是一个错误尝试使用map和lambda函数的组合:
aList = map( lambda x: x, set ([1, 2, 6, 9, 0]) )
如果您有一组字符串中的数字,并且希望将其转换为整数列表,则这是一种非常方便的方法:
aList = map( lambda x: int(x), set (['1', '2', '3', '7', '12']) )
这将有助于:
>>> t = [1,1,2,2,3,3,4,5]
>>> print list(set(t))
[1,2,3,4,5]
但是,如果使用“list”或“set”作为变量名,则会得到:
TypeError: 'set' object is not callable
例如:
>set=[1,1,2,2,3,3,4,5]
>>>打印列表(套)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:“列表”对象不可调用
如果您将“list”用作变量名,则会出现相同的错误。在编写set(XXXXX)
您已使用“set”作为变量
e、 g
以上内容在Python 2.7上适用。如果您在代码
集合中命名了另一个变量
更改它,因为您正在隐藏内置函数集合
@mouad No,则TypeError
中括号中的字符串是类型的名称,而不是变量name@Judge约翰·迪德:你确实在某处做了些什么。在调用前添加print list
。我在PDB中调试时遇到了这个问题,其中“list”作为PDB命令被覆盖。我只是在空闲状态下复制并粘贴了这个精确的代码;我得到错误。你能提供dir(set)
和print set
的输出吗?['and','class','cmp','contains','delattr','doc','eq','format','ge','GETATTER','gt','hash','iand','INT','ior','isub','iter','ixor','le','len','lt','ne','new','or','rand','repr','ror','rsub rxor','rxor','str sub','sub','subclasshook','xor','add','clear','clear','COP,“差异更新”、“放弃”、“交叉”、“交叉更新”、“ISDISJOIN”、“issubset”、“issuperset”、“pop”、“删除”、“对称差异”、“对称差异更新”、“联合”、“更新”]
(因字符限制而删除)@约翰·迪德法官:您在哪一行出现错误?您的集合看起来不错。请尝试集合而不是集合:REF:
>>> t = [1,1,2,2,3,3,4,5]
>>> print list(set(t))
[1,2,3,4,5]
TypeError: 'set' object is not callable
>>> set = [1,1,2,2,3,3,4,5]
>>> print list(set(set))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
set = 90 #you have used "set" as an object
…
…
a = set(["Blah", "Hello"])
a = list(a)