Python 數(shù)字轉(zhuǎn)化成列表詳情
本篇閱讀的代碼實(shí)現(xiàn)了將輸入的數(shù)字轉(zhuǎn)化成一個(gè)列表,輸入數(shù)字中的每一位按照從左到右的順序成為列表中的一項(xiàng)。
本篇閱讀的代碼片段來(lái)自于30-seconds-of-python。
1. digitize
def digitize(n): return list(map(int, str(n))) # EXAMPLES digitize(123) # [1, 2, 3]
該函數(shù)的主體邏輯是先將輸入的數(shù)字轉(zhuǎn)化成字符串,再使用map
函數(shù)將字符串按次序轉(zhuǎn)花成int
類型,最后轉(zhuǎn)化成list
。
為什么輸入的數(shù)字經(jīng)過(guò)這種轉(zhuǎn)化就可以得到一個(gè)列表呢?這是因?yàn)?code>Python中str
是一個(gè)可迭代類型。所以str
可以使用map
函數(shù),同時(shí)map
返回的是一個(gè)迭代器,也是一個(gè)可迭代類型。最后再使用這個(gè)迭代器構(gòu)建一個(gè)列表。
2. Python判斷對(duì)象是否可迭代
目前網(wǎng)絡(luò)上的常見(jiàn)的判斷方法是使用使用collections.abc
(該模塊在3.3以前是collections
的組成部分)模塊的Iterable
類型來(lái)判斷。
from collections.abc import Iterable isinstance('abc', Iterable) # True isinstance(map(int,a), Iterable) # True
雖然在當(dāng)前場(chǎng)景中這么使用沒(méi)有問(wèn)題,但是根據(jù)官方文檔的描述,檢測(cè)一個(gè)對(duì)象是否是iterable
的唯一可信賴的方法是調(diào)用iter(obj)
。
class collections.abc.Iterable
ABC for classes that provide the __iter__() method.Checking isinstance(obj, Iterable) detects classes that are registered as Iterable or that have an __iter__() method, but it does not detect classes that iterate with the __getitem__() method. The only reliable way to determine whether an object is iterable is to call iter(obj).
>>> iter('abc') <str_iterator object at 0x10c6efb10>
到此這篇關(guān)于Python 數(shù)字轉(zhuǎn)化成列表詳情的文章就介紹到這了,更多相關(guān)Python 數(shù)字轉(zhuǎn)化成列表內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。