Python-如何在嵌套列表上实现zfill

时间:2019-03-13 20:11:27

标签: python

我已经发布了有关此代码的另一个问题,并且在尝试进一步开发该代码时,我偶然发现了一个错误。我想使嵌套列表更易于显示,而这次遇到的问题与zfill有关。尝试将嵌套列表中的每个元素更改为2位数字以使事情看起来更加整洁时,我犯了一个错误。当我运行以下代码时,数字不是2位数字-

import random

def random_2d_array(rows, columns):
    output = []
    iteration = 0
    while iteration != rows:
        i2 = 0
        iteration += 1
        output.append([])
        while i2 != columns:
            i2 += 1
            num = random.randint(1, 10)
            col = output[iteration - 1]
            col.insert(i2 - 1, num)
    for i in output:
        for j in i:
            j = str(j)
            j = j.zfill(2)
    return '\n'.join([str(i) for i in output])

print(random_2d_array(10, 10))

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

j之后您没有使用j = j.zfill(2)。您必须将列表中的元素设置为该值:

import random

def random_2d_array(rows, columns):
    output = []
    iteration = 0
    while iteration != rows:
        i2 = 0
        iteration += 1
        output.append([])
        while i2 != columns:
            i2 += 1
            num = random.randint(1, 10)
            col = output[iteration - 1]
            col.insert(i2 - 1, num)
    for i in output:
        for j in range(len(i)):
            s = str(i[j])
            i[j] = s.zfill(2)
    return '\n'.join([str(i) for i in output])

print(random_2d_array(10, 10))

结果:

['01', '03', '08', '03', '06', '03', '06', '10', '10', '08']
['08', '08', '06', '04', '10', '03', '04', '06', '10', '06']
['07', '04', '03', '02', '02', '04', '10', '04', '07', '06']
['05', '10', '10', '04', '09', '09', '03', '10', '09', '09']
['08', '09', '09', '10', '06', '04', '08', '09', '05', '05']
['06', '02', '05', '01', '05', '07', '01', '06', '03', '08']
['06', '06', '04', '09', '06', '01', '02', '10', '08', '01']
['08', '10', '10', '05', '10', '10', '02', '06', '10', '09']
['08', '07', '04', '08', '03', '03', '02', '08', '03', '10']
['10', '07', '02', '07', '05', '05', '10', '04', '06', '08']

编辑:如果要删除引号,请使用

return '\n'.join([str(i) for i in output]).replace('\'','')

作为函数的最后一行。