我想填充我的2D数组中的第一列和第一行,使用字符串中的字母,如示例所示。 我的代码填充的行数和给定的长度一样......你能帮助我吗?
字符串1 = 'polujsj' 字符串2 = 'ksjuhjjj'
array:
p o l u j s j
k 0 0 0 0 0 0 0
s 0 0 0 0 0 0 0
j 0 0 0 0 0 0 0
u 0 0 0 0 0 0 0
h 0 0 0 0 0 0 0
j 0 0 0 0 0 0 0
j 0 0 0 0 0 0 0
j 0 0 0 0 0 0 0
我的代码:
a=len(string1)
b=len(string2)
matrix= [ [ 0 for i in range(a+1) ] for j in range(b+1) ]
for n in range(0,a+1):
for letters in string1:
matrix[0][n]=letters
for rows in matrix:
print rows
如何实现上述效果?
答案 0 :(得分:1)
这样的事情可能是:
string1 = 'polujsj'
string2 = 'ksjuhjjj'
firstLine = list(' ' + string1)
matrix = [firstLine] + [[c] + [0] * len(string1) for c in string2]
for line in matrix:
print(' '.join(map(str, line)))
打印:
p o l u j s j
k 0 0 0 0 0 0 0
s 0 0 0 0 0 0 0
j 0 0 0 0 0 0 0
u 0 0 0 0 0 0 0
h 0 0 0 0 0 0 0
j 0 0 0 0 0 0 0
j 0 0 0 0 0 0 0
j 0 0 0 0 0 0 0
答案 1 :(得分:1)
也许你想要一个零矩阵。您可以构建输出字符串:
string1='polujsj'
string2='ksjuhjjj'
a=len(string1)
b=len(string2)
matrix= [ [ 0 for i in range(a) ] for j in range(b) ]
out = ' '
for letter in string1:
out += letter + ' '
for i in range(b):
out += '\n' + string2[i] + ' '
for item in matrix[i]:
out += str(item) + ' '
print(out)