如何将字符列表的每个元素插入矩阵(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)
现在,我想将text_c中的每个元素插入到矩阵中。无论该矩阵是否填满。 我怎样才能做到这一点。谢谢 (抱歉我的英语不好)
答案 0 :(得分:1)
您可以通过组合一些列表推导来实现此目的:
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]
给予matrix
:
[['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_string
切片到所需长度(列数)的子字符串,这些子字符串在切片后转换为列表。
在示例代码中,我提供的sample_string
不能被给定的number_colums
整除,这意味着子字符串efgh
的最后一个列表没有所需的{{1}长度}。为了解决这个问题,我们需要检查每个列表的长度是否符合要求。如果没有,我们会追加所需数量的number_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]