在 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.
解决方案
应用相同zfill
函数,像这样
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
返回一个可迭代的 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']
相关文章