Python 数字转化成列表详情
本篇阅读的代码实现了将输入的数字转化成一个列表,输入数字中的每一位按照从左到右的顺序成为列表中的一项。
本篇阅读的代码片段来自于30-seconds-of-python。
1. digitize
def digitize(n): return list(map(int, str(n))) # EXAMPLES digitize(123) # [1, 2, 3]
该函数的主体逻辑是先将输入的数字转化成字符串,再使用map
函数将字符串按次序转花成int
类型,最后转化成list
。
为什么输入的数字经过这种转化就可以得到一个列表呢?这是因为Python
中str
是一个可迭代类型。所以str
可以使用map
函数,同时map
返回的是一个迭代器,也是一个可迭代类型。最后再使用这个迭代器构建一个列表。
2. 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 数字转化成列表详情的文章就介绍到这了,更多相关Python 数字转化成列表内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!
版权声明:本站文章来源标注为YINGSOO的内容版权均为本站所有,欢迎引用、转载,请保持原文完整并注明来源及原文链接。禁止复制或仿造本网站,禁止在非www.yingsoo.com所属的服务器上建立镜像,否则将依法追究法律责任。本站部分内容来源于网友推荐、互联网收集整理而来,仅供学习参考,不代表本站立场,如有内容涉嫌侵权,请联系alex-e#qq.com处理。