問題描述
我是 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']
這篇關于在 Python 中的數字列表中添加前導零的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!