在 python 中将 range(r) 转换为长度为 2 的字符串列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17577797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert range(r) to list of strings of length 2 in python
提问by KevinShaffer
I just want to change a list (that I make using range(r)) to a list of strings, but if the length of the string is 1, tack a 0 on the front. I know how to turn the list into strings using
我只想将一个列表(我使用 range(r) 制作的)更改为一个字符串列表,但如果字符串的长度为 1,则在前面添加一个 0。我知道如何使用
ranger= map(str,range(r))
but I want to be able to also change the length of those strings.
但我也希望能够改变这些字符串的长度。
Input:
输入:
r = 12
ranger = range(r)
ranger = magic_function(ranger)
Output:
输出:
print ranger
>>> ['00','01','02','03','04','05','06','07','08','09','10','11']
And if possible, my final goal is this: I have a matrix of the form
如果可能的话,我的最终目标是:我有一个矩阵
numpy.array([[1,2,3],[4,5,6],[7,8,9]])
and I want to make a set of strings such that the first 2 characters are the row, the second two are the column and the third two are '01', and have matrix[row,col] of each one of these. so the above values would look like such:
我想制作一组字符串,前两个字符是行,后两个是列,第三个是 '01',并且每个字符都有矩阵 [row,col]。所以上面的值看起来像这样:
000001 since matrix[0,0] = 1
000101 since matrix[0,1] = 2
000101 since matrix[0,1] = 2
000201
000201
000201
etc
采纳答案by Ashwini Chaudhary
Use string formatting
and list comprehension:
使用string formatting
和列表理解:
>>> lst = range(11)
>>> ["{:02d}".format(x) for x in lst]
['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10']
or format
:
或format
:
>>> [format(x, '02d') for x in lst]
['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10']
回答by arshajii
Here's my take on it:
这是我的看法:
>>> map('{:02}'.format, xrange(12))
['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11']
For your own enlightenment, try reading about the format string syntax.
为了您自己的启蒙,请尝试阅读格式字符串语法。
回答by Ludo
Use string formatting:
使用字符串格式:
>>> sr = []
>>> for r in range(11):
... sr.append('%02i' % r)
...
>>> sr
['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10']
回答by kindall
zfill
does exactly what you want and doesn't require you to understand an arcane mini-language as with the various types of string formatting. There's a place for that, but this is a simple job with a ready-made built-in tool.
zfill
完全符合您的要求,并且不需要您像各种类型的字符串格式一样理解一种神秘的迷你语言。这是一个地方,但这是一个简单的工作,有一个现成的内置工具。
ranger = [str(x).zfill(2) for x in range(r)]