如何将字符列表的元素添加到 nxm 数组中?
我在python中有这段代码。
key = raw_input('Key: ') #Pedimos la clave
text = raw_input('Text: ') #Pedimos una cadena de texto
text_c = list(text) #Pasamos la cadena a una lista de caracteres
while ' ' in text_c: #quitamos los espacios
text_c.remove(' ')
#caculo de las columnas y renglones
columns = len(key)
rows = int(math.ceil(float(len(text_c)) / float(len(key))) )
#Definicion de una matriz
matrix = []
for i in range(rows):
matrix.append([])
for j in range(columns):
matrix[i].append(None)
我想要做的是用列表中的字符填充数组。
例如用户输入:key:HELLO,text:this is text
该程序生成一个 3 行乘 4 列的矩阵,我想用文本字符填充该矩阵,以这种方式:
[e,s,t,o]
[e,s,u,n]
[t,e,x,t]
[o,none,none,none]
谢谢您的回答
你实际上已经完成了。按照您的示例,这是缺少的:
定义一个变量来计算字符
每次迭代的增量
也就是说,随着 2 个循环的进行,它增加 1
将该位置的字符添加为行中的新列
i
...除非没有更多的字符
代码
结果:
[['e', 's', 't', 'o'], ['e', 's', 'u', 'n'], ['t', 'e', 'x', 't'], ['o', None, None, None]]
Demo en ideone.com
应该注意的是,有更紧凑或Pythonic 的方法可以做到这一点,但在我看来,这似乎是解释该主题的最佳选择。
我能够通过以下方式解决它。如果有人发现它有用,这是代码: