在python中转换和修改列表

时间:2015-12-19 13:40:54

标签: python string list python-2.7

在一些数学运算之后,我有一个如此获得的列表:

[[899, 6237], [898, 6237], [897, 6237],
 [896, 6237], [895, 6237], [899, 6238],
 [898, 6238], [897, 6238], [896, 6238],
 [895, 6238], [899, 6239], [898, 6239],
 [897, 6239], [896, 6239], [895, 6239],
 [899, 6240], [898, 6240], [897, 6240],
 [896, 6240], [895, 6240]]

我希望每个子列表的组件成为4个字符大小的字符串。这是我想要的主列表的第一个元素的例子:

['0899','6237']

4 个答案:

答案 0 :(得分:2)

使用https://technet.microsoft.com/en-us/library/aa196339(v=sql.80).aspxlist comprehension

>>> lst = [
...     [899, 6237], [898, 6237], [897, 6237], [896, 6237], [895, 6237],
...     [899, 6238], [898, 6238], [897, 6238], [896, 6238], [895, 6238],
...     [899, 6239], [898, 6239], [897, 6239], [896, 6239], [895, 6239],
...     [899, 6240], [898, 6240], [897, 6240], [896, 6240], [895, 6240],
... ]
>>> [[format(a, '04'), format(b, '04')] for a, b in lst]
[['0899', '6237'], ['0898', '6237'], ['0897', '6237'], ['0896', '6237'],
 ['0895', '6237'], ['0899', '6238'], ['0898', '6238'], ['0897', '6238'],
 ['0896', '6238'], ['0895', '6238'], ['0899', '6239'], ['0898', '6239'],
 ['0897', '6239'], ['0896', '6239'], ['0895', '6239'], ['0899', '6240'],
 ['0898', '6240'], ['0897', '6240'], ['0896', '6240'], ['0895', '6240']]

您还可以使用format

>>> '{:04}'.format(899)
'0899'

str.format

>>> '%04d' % 899
'0899'

答案 1 :(得分:0)

您可以zfill使用list comprehension

list_name = [[str(i).zfill(4) for i in element] for element in your_list]

演示:

>>>str(890).zfill(4)
'0890'
>>>str(890).zfill(5)
'00890'

答案 2 :(得分:0)

您可以使用简单的list comprehension

new_list = [['0' + str(i[0]), str(i[1])]  for i in original_list]

new_list输出:

[['0899', '6237'], ['0898', '6237'], ['0897', '6237'], ['0896', '6237'], ['0895', '6237'], ['0899', '6238'], ['0898', '6238'], ['0897', '6238'], ['0896', '6238'], ['0895', '6238'], ['0899', '6239'], ['0898', '6239'], ['0897', '6239'], ['0896', '6239'], ['0895', '6239'], ['0899', '6240'], ['0898', '6240'], ['0897', '6240'], ['0896', '6240'], ['0895', '6240']]

答案 3 :(得分:0)

正确的方法是使用format(),虽然zfill也非常甜。 这是一个非常丑陋的解决方案,任何人都不应该使用:

list = [
 [899, 6237], [898, 6237], [897, 6237], [896, 6237], [895, 6237], [899, 6238],
 [898, 6238], [897, 6238], [896, 6238], [895, 6238], [899, 6239], [898, 6239],
 [897, 6239], [896, 6239], [895, 6239], [899, 6240], [898, 6240], [897, 6240],
 [896, 6240], [895, 6240]
]

def yolo(pair):
    pair = map(str,pair)
    return ['0'*(4-len(pair[0])) + pair[0], pair[1]]

list = map(yolo,list)