Python 數(shù)字轉化成列表詳情
本篇閱讀的代碼實現(xiàn)了將輸入的數(shù)字轉化成一個列表,輸入數(shù)字中的每一位按照從左到右的順序成為列表中的一項。
本篇閱讀的代碼片段來自于30-seconds-of-python。
1. digitize
def digitize(n): return list(map(int, str(n))) # EXAMPLES digitize(123) # [1, 2, 3]
該函數(shù)的主體邏輯是先將輸入的數(shù)字轉化成字符串,再使用map
函數(shù)將字符串按次序轉花成int
類型,最后轉化成list
。
為什么輸入的數(shù)字經過這種轉化就可以得到一個列表呢?這是因為Python
中str
是一個可迭代類型。所以str
可以使用map
函數(shù),同時map
返回的是一個迭代器,也是一個可迭代類型。最后再使用這個迭代器構建一個列表。
2. Python判斷對象是否可迭代
目前網絡上的常見的判斷方法是使用使用collections.abc
(該模塊在3.3以前是collections
的組成部分)模塊的Iterable
類型來判斷。
from collections.abc import Iterable isinstance('abc', Iterable) # True isinstance(map(int,a), Iterable) # True
雖然在當前場景中這么使用沒有問題,但是根據(jù)官方文檔的描述,檢測一個對象是否是iterable
的唯一可信賴的方法是調用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>
到此這篇關于Python 數(shù)字轉化成列表詳情的文章就介紹到這了,更多相關Python 數(shù)字轉化成列表內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
對Python3中dict.keys()轉換成list類型的方法詳解
今天小編就為大家分享一篇對Python3中dict.keys()轉換成list類型的方法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02python scipy.misc.imsave()函數(shù)的用法說明
這篇文章主要介紹了python scipy.misc.imsave()函數(shù)的用法說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-05-05python內置函數(shù):lambda、map、filter簡單介紹
Python 內置了一些比較特殊且實用的函數(shù),使用這些能使你的代碼簡潔而易讀。下面對python內置函數(shù):lambda、map、filter簡單介紹下,需要的朋友參考下吧2017-11-11python pandas最常用透視表實現(xiàn)應用案例
透視表是一種可以對數(shù)據(jù)動態(tài)排布并且分類匯總的表格格式,它在數(shù)據(jù)分析中有著重要的作用和地位,在本文中,我將為你介紹python中如何使用pandas包實現(xiàn)透視表的功能,以及一些常見的應用案例2024-01-01