[英]Lists accept iterable objects as inputs. However, when the input is an int or float, e.g. list(1), this is not accepted. Why?
I was experimenting with list properties while doing Python exercises on inheritance and class objects. 我在对继承和类对象进行Python练习时正在尝试使用列表属性。 I realised that
list([1,2,3])
is valid as a list itself is an iterable but something like list(1)
will return an error. 我意识到
list([1,2,3])
是有效的,因为列表本身是可迭代的,但是类似list(1)
东西将返回错误。 Isn't a single object in itself an iterable? 单个对象本身不是可迭代的吗? However, a string with multiple characters like list("this is a list") does not return an error, further adding to my confusion (Granted, a string is a single object).
但是,具有多个字符的字符串(例如list(“ this is a list”))不会返回错误,这进一步加剧了我的困惑(当然,字符串是单个对象)。 Why is that the case?
为什么会这样?
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]*/
I've looked at the source code for the list class at https://github.com/python/cpython/blob/master/Objects/listobject.c and it seems line 2675-2721 might have the answer I'm looking for but as a novice, I need someone to explain the process of creating a list to me. 我已经在https://github.com/python/cpython/blob/master/Objects/listobject.c上查看了列表类的源代码,似乎第2675-2721行可能具有我正在寻找的答案但作为新手,我需要有人向我解释创建列表的过程。
The list()
function only accepts iterables. list()
函数仅接受可迭代。 Iterables are objects that can be iterated over. 可迭代对象是可以迭代的对象。 There is no way a program can iterate over an integer, but it can iterate over a single-character string.
程序无法迭代整数,但是可以迭代单字符字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.