在Python的数字列表中添加前导零 [英] add leading zeros to a list of numbers in Python

查看:256
本文介绍了在Python的数字列表中添加前导零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手.我正在尝试调整如下所示的列表格式:

I am new to Python. I am trying to adjust the format of a list which looks like below:

data=[1,10,313,4000,51234,123456]

,我想将它们转换为带有前导零的字符串列表:

and I would like to convert them to a list of strings with leading zeros:

result=['000001','000010','000313','004000','051234','123456']

每个元素都有6位数字.

each of the element has 6 digits.

我知道一个数字X,我可以做到:

I know for a single number X, I can do:

str(X).zfill(6)

但是我不确定如何将其应用于列表.我想在不使用for循环的情况下解决此问题.

but I am not sure how to apply this to a list. I would like to solve this problem without using a for loop.

任何人都可以帮忙吗?谢谢.

Anyone could help? Thanks.

推荐答案

应用相同的 函数,例如列表理解

Apply the same zfill function in a list comprehension, like this

>>> [str(item).zfill(6) for item in data]
['000001', '000010', '000313', '004000', '051234', '123456']

或者,您可以将字符串的 format 方法与格式说明符,例如

Alternatively, you can use the string's format method, with format specifiers, like this

>>> ["{:06d}".format(item) for item in data]
['000001', '000010', '000313', '004000', '051234', '123456']

如果您要更频繁地进行格式化,则可以将其存储在这样的变量中

If you are going to do the formatting more often, then you can store that in a variable, like this

>>> formatter = "{:06d}".format
>>> [formatter(item) for item in data]
['000001', '000010', '000313', '004000', '051234', '123456']

如果您使用的是Python 2.x,则可以使用 map formatter函数,就像这样

If you are using Python 2.x, then you can use map and the formatter function, like this

>>> map(formatter, data)
['000001', '000010', '000313', '004000', '051234', '123456']

如果您使用的是Python 3.x,则 map 返回可迭代的对象.因此,您需要像这样显式创建一个列表

If you are using Python 3.x, map returns an iterable map object. So, you need to explicitly create a list, like this

>>> list(map(formatter, data))
['000001', '000010', '000313', '004000', '051234', '123456']

这篇关于在Python的数字列表中添加前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆