在 python 中我可以做这样的事情:
d = dict()
i = int()
f = float()
l = list()
但是字符串没有构造函数
>>> s = string()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'string' is not defined
这是为什么呢?或者,是否有字符串类型的构造函数?
另外,按照上面的定义,
d['a'] = 1
有效,但是
>>> l[0] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
没有。
有人能给我解释一下吗?
最佳答案
你的意思是:
a = str()
我相信。然后一切正常。
关于d['a']
和l[0]
的区别:d
是一个字典,它有一个存储元素的稀疏表示。而列表 (l
) 密集地表示数据:所以如果您有:
l = [1,2]
你随后写道:
l[200] = 31
这意味着,除了分配给元素 200 之外,要完全一致,还要在 l[3:199]
中放置一些任意值。
关于python - python 中类型构造函数的奇怪之处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11403046/