关于python:Python代码阅读第2篇数字转化成列表

4次阅读

共计 944 个字符,预计需要花费 3 分钟才能阅读完成。

本篇浏览的代码实现了将输出的数字转化成一个列表,输出数字中的每一位依照从左到右的程序成为列表中的一项。

本篇浏览的代码片段来自于 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>
正文完
 0