Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用特定值填充二维数组_Python_Arrays - Fatal编程技术网

Python 用特定值填充二维数组

Python 用特定值填充二维数组,python,arrays,Python,Arrays,我想用字符串中的字母填充2D数组的第一列和第一行,如示例所示。 我的代码正在填充给定长度的行数。。。你能帮我吗 string1='polujsj' string2='ksjuhjj' 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 我的代码:

我想用字符串中的字母填充2D数组的第一列和第一行,如示例所示。 我的代码正在填充给定长度的行数。。。你能帮我吗

string1='polujsj' string2='ksjuhjj'

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

我怎样才能达到上面的效果呢?

像这样的可能:

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

也许你想要一个由零组成的矩阵。您可以生成输出字符串:

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)