Python代码阅读(第2篇):数字转化成列表
2021/10/2 13:10:04
本文主要是介绍Python代码阅读(第2篇):数字转化成列表,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
本篇阅读的代码实现了将输入的数字转化成一个列表,输入数字中的每一位按照从左到右的顺序成为列表中的一项。
本篇阅读的代码片段来自于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>
这篇关于Python代码阅读(第2篇):数字转化成列表的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-23Python中理解和使用树形结构的简单教程
- 2024-09-23Python 编程基础入门
- 2024-09-18初探Python股票自动化交易:入门指南
- 2024-09-18Python量化入门:轻松掌握量化分析基础与实战
- 2024-09-18Python量化交易:入门指南与实践
- 2024-09-18Python量化交易:入门指南与实战技巧
- 2024-09-14Python人工智能项目实战:从零开始的实践指南
- 2024-09-14探索Python人工智能资料:初学者的指南
- 2024-09-14Python人工智能资料:初学者的全面指南
- 2024-09-13Matplotlib入门:轻松绘制Python数据可视化图表