为了账号安全,请及时绑定邮箱和手机立即绑定

Python代码阅读(第2篇):数字转化成列表

标签:
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>
点击查看更多内容
1人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消