1. 程式人生 > 其它 >Python程式碼閱讀(第2篇):數字轉化成列表

Python程式碼閱讀(第2篇):數字轉化成列表

本篇閱讀的程式碼實現了將輸入的數字轉化成一個列表,輸入數字中的每一位按照從左到右的順序成為列表中的一項。 本篇閱讀的程式碼片段來自於30-seconds-of-python。

本篇閱讀的程式碼實現了將輸入的數字轉化成一個列表,輸入數字中的每一位按照從左到右的順序成為列表中的一項。

本篇閱讀的程式碼片段來自於30-seconds-of-python

digitize

def digitize(n):
  return list(map(int, str(n)))

# EXAMPLES
digitize(123) # [1, 2, 3]

該函式的主體邏輯是先將輸入的數字轉化成字串,再使用map函式將字串按次序轉花成int型別,最後轉化成list

為什麼輸入的數字經過這種轉化就可以得到一個列表呢?這是因為Python中str是一個可迭代型別。所以str可以使用map

函式,同時map返回的是一個迭代器,也是一個可迭代型別。最後再使用這個迭代器構建一個列表。

Python判斷物件是否可迭代

目前網路上的常見的判斷方法是使用使用collections.abc(該模組在3.3以前是collections的組成部分)模組的Iterable型別來判斷。

from collections.abc import Iterable
isinstance('abc', Iterable) # True
isinstance(map(int,a), Iterable) # True

雖然在當前場景中這麼使用沒有問題,但是根據官方文件的描述,檢測一個物件是否是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>