打印间隔可变的列表

时间:2018-09-05 10:29:44

标签: python string python-3.x

我正在寻找python3代码以获取81个数字的列表,例如 这个:

003020600900305001001806400008102900700000008006708200002609500800203009005010300

并以9x9公制格式打印,水平数字之间的距离较大:

003020600 900305001 001806400
008102900 700000008 006708200
002609500 800203009 005010300

3 个答案:

答案 0 :(得分:1)

使用slicing

例如:

s =  '003020600900305001001806400008102900700000008006708200002609500800203009005010300'

for i in range(0, len(s), 27):
    val = s[i:i+27]
    print( " ".join(val[j:j+9] for j in range(0, len(val), 9)) )

输出:

003020600 900305001 001806400
008102900 700000008 006708200
002609500 800203009 005010300

根据评论进行编辑。

for i in range(0, len(s), 27):
    val = s[i:i+27]
    for j in range(0, len(val), 9):
            print(" ".join(val[j:j + 9]))

输出:

0 0 3 0 2 0 6 0 0
9 0 0 3 0 5 0 0 1
0 0 1 8 0 6 4 0 0
0 0 8 1 0 2 9 0 0
7 0 0 0 0 0 0 0 8
0 0 6 7 0 8 2 0 0
0 0 2 6 0 9 5 0 0
8 0 0 2 0 3 0 0 9
0 0 5 0 1 0 3 0 0

答案 1 :(得分:0)

用于空格和行中断

st = '003020600900305001001806400008102900700000008006708200002609500800203009005010300'
metric_size = 9
space_interval = 3
index = 1

for i in range(0, len(st), metric_size):

    print(st[i:i + metric_size], end=' ')

    if index%space_interval == 0:
        print()

    index += 1

输出

003020600 900305001 001806400 
008102900 700000008 006708200 
002609500 800203009 005010300 

针对线路中断

st = '003020600900305001001806400008102900700000008006708200002609500800203009005010300'
metric_size = 9
space_interval = 3
index = 1

for i in range(0, len(st), metric_size):

    print(st[i:i + metric_size])

    if index%space_interval == 0:
        print("---------")

    index += 1

输出

003020600
900305001
001806400
---------
008102900
700000008
006708200
---------
002609500
800203009
005010300
---------

答案 2 :(得分:0)

这是一种假设您提供每个数字的位数和每行数字的一种方法。

x = '003020600900305001001806400008102900700000008006708200002609500800203009005010300'

num_len = 9
num_row = 3

L = [x[i:i+num_len] for i in range(0, len(x), num_len)]
res = (L[j:j+num_row] for j in range(0, len(L), num_row))

print(*(' '.join(i) for i in res), sep='\n')

003020600 900305001 001806400
008102900 700000008 006708200
002609500 800203009 005010300