温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python如何将数字转化成列表

发布时间:2021-11-11 13:30:58 来源:亿速云 阅读:2895 作者:小新 栏目:开发技术

小编给大家分享一下Python如何将数字转化成列表,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

1. digitize

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

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

该函数的主体逻辑是先将输入的数字转化成字符串,再使用map函数将字符串按次序转花成int类型,最后转化成list

为什么输入的数字经过这种转化就可以得到一个列表呢?这是因为Pythonstr是一个可迭代类型。所以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如何将数字转化成列表”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI