gpt4 book ai didi

python - 生成特定格式的数字列表

转载 作者:太空狗 更新时间:2023-10-29 17:02:35 28 4
gpt4 key购买 nike

我需要生成特定格式的数字列表。格式是

mylist = [00,01,02,03,04,05,06,07,08,09,10,11,12,13,14,15]
#Numbers between 0-9 are preceded by a zero.

我知道如何使用 range 生成一个普通的数字列表

>>> for i in range(0,16):
... print i

那么,python中有没有内置的方法来生成指定格式的数字列表。

最佳答案

python string formatting允许您指定精度:

Precision (optional), given as a '.' (dot) followed by the precision.

在这种情况下,您可以使用它的值为 2 来获得您想要的:

>>> ["%.2d" % i for i in range(16)]
['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12',
'13', '14', '15']

您还可以使用 zfill 函数:

>>> str(3).zfill(2)
'03'

或者字符串格式化函数:

>>> "{0:02d}".format(3)
'03'

关于python - 生成特定格式的数字列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12030074/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com