簡體   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