如何在python中将字符列表的每个元素插入到矩阵中

如何在python中将字符列表的每个元素插入到矩阵中,python,list,matrix,Python,List,Matrix,如何将字符列表的每个元素插入矩阵(mxn) 我用python编写了这段代码 key = raw_input('Key: ') text = raw_input('Text: ') text_c = list(text) while ' ' in text_c: text_c.remove(' ') columns = len(key) rows = int(math.ceil(float(len(text_c)) / float(len(key))) )

如何将字符列表的每个元素插入矩阵(mxn) 我用python编写了这段代码

key = raw_input('Key: ')
text = raw_input('Text: ')
text_c = list(text)
while ' ' in text_c:
  text_c.remove(' ')     
columns = len(key)              
rows = int(math.ceil(float(len(text_c)) / float(len(key))) )
matrix = []
for i in range(rows):
    matrix.append([])
    for j in range(columns):
        matrix[i].append(None)
现在,我想将文本_c中的每个元素插入到矩阵中。不管矩阵是否填满。 我怎样才能做到这一点。谢谢
(对不起,我的英语不好)

您可以通过结合以下列表理解来实现这一点:

number_columns = 6
sample_string = 'abcdefghijklmnopqrstuvwxyzabcdefgh'

l = [list(sample_string[i:i+number_columns]) for i in range(0, len(sample_string), number_columns)]
matrix = [s if len(s) == number_columns else s+[None]*(number_columns-len(s)) for s in l]
为矩阵给出:

[['a', 'b', 'c', 'd', 'e', 'f'],
 ['g', 'h', 'i', 'j', 'k', 'l'],
 ['m', 'n', 'o', 'p', 'q', 'r'],
 ['s', 't', 'u', 'v', 'w', 'x'],
 ['y', 'z', 'a', 'b', 'c', 'd'],
 ['e', 'f', 'g', 'h', None, None]]
首先,我们将
sample\u字符串
切片为所需长度(列数)的子字符串,这些子字符串在切片后转换为列表

在我提供的示例代码中,
sample\u string
不能被给定的
number\u columns
平均整除,这意味着子字符串
efgh
的最后一个列表没有所需的
number\u columns
长度。为了解决这个问题,我们需要检查每个列表的长度是否符合要求。如果没有,我们将添加所需数量的
None
元素

为了去掉任何空格,我们需要通过

sample_string = sample_string.replace(' ', '')
它将用空字符串替换任何空格。所以

number_columns = 6
sample_string = 'this is a sample string'

sample_string = sample_string.replace(' ', '')

l = [list(sample_string[i:i+number_columns]) for i in range(0, len(sample_string), number_columns)]
matrix = [s if len(s) == number_columns else s+[None]*(number_columns-len(s)) for s in l]
会导致

[['t', 'h', 'i', 's', 'i', 's'],
 ['a', 's', 'a', 'm', 'p', 'l'],
 ['e', 's', 't', 'r', 'i', 'n'],
 ['g', None, None, None, None, None]]

您能提供一个输入和输出代码段示例,并使您的代码完全可运行吗?例如,
tabla
在您提供的代码中没有正确定义。对不起,tabla是矩阵。我已经纠正了它,那么-/output中的示例又如何呢?此外:
key
do做什么?key给出了许多矩阵列。我试着做一个加密算法。用户编写一个键和一个文本字符串。程序根据这些元素计算行数和列数。如果这解决了您的问题,请接受我的回答,以便将您的问题标记为已解决。完成!谢谢,我是新来的