繁体   English   中英

列表接受可迭代对象作为输入。 但是,当输入为int或float时,例如list(1),则不接受此输入。 为什么?

[英]Lists accept iterable objects as inputs. However, when the input is an int or float, e.g. list(1), this is not accepted. Why?

我在对继承和类对象进行Python练习时正在尝试使用列表属性。 我意识到list([1,2,3])是有效的,因为列表本身是可迭代的,但是类似list(1)东西将返回错误。 单个对象本身不是可迭代的吗? 但是,具有多个字符的字符串(例如list(“ this is a list”))不会返回错误,这进一步加剧了我的困惑(当然,字符串是单个对象)。 为什么会这样?

from  cpython/listobject.c (starting line 2675)
/*[clinic input]
list.__init__
    iterable: object(c_default="NULL") = ()
    /
Built-in mutable sequence.
If no argument is given, the constructor creates a new empty list.
The argument must be an iterable if specified.
[clinic start generated code]*/

我已经在https://github.com/python/cpython/blob/master/Objects/listobject.c上查看了列表类的源代码,似乎第2675-2721行可能具有我正在寻找的答案但作为新手,我需要有人向我解释创建列表的过程。

list()函数仅接受可迭代。 可迭代对象是可以迭代的对象。 程序无法迭代整数,但是可以迭代单字符字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM