gpt4 book ai didi

python - 如何在 Python 中创建包含不同变量的列表(矩阵)列表?

转载 作者:太空宇宙 更新时间:2023-11-03 17:53:44 25 4
gpt4 key购买 nike

我目前正在使用 Python 语言,我正在尝试创建一个类,该类充当包含 4 个并行列表的矩阵,其长度等于给定句子的长度。每个列表都有自己的行并包含不同的变量。然而,我在尝试将句子的每个字母打印到第 2 行时遇到了麻烦。我如何通过迭代(而不是手动附加它们)来实现这一目标?

出于视觉目的,最终结果需要如下所示:

Row 1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Row 2 = [h, e, l, l, o, , w, o, r, l, d]
Row 3 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Row 4 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

下面是我当前的代码。

class Matrix(object):#,Sentence, Cipher_Sentence
def __init__ (self, cols, rows):#, Nav):#, Guess, Crypt, Sent):
self.cols=cols
self.rows=rows
self.sentence=sentence
self.matrix=[]
for i in range (rows):
ea_row=[]
for j in range (cols):
ea_row.append(0)
self.matrix.append(ea_row)

def set_Nav(self, col, row, Nav):
self.matrix[col-1][0]=Nav
def get_Nav(self, col, row):
return self.matrix[col-1][0]

def set_Guess(self, col, row, Guess):
self.matrix[col-1][1]=Guess
def get_Guess(self, col, row):
return self.matrix[col-1][1]

def set_Crypt(self, col, row, Crypt):
self.matrix[col-1][2]=Crypt
def get_Crypt(self, col, row):
return self.matrix[col-1][2]

def set_Sent(self, col, row, Sent):
self.matrix[col-1][3]=Sent
def get_Sent(self, col, row):
return self.matrix[col-1][3]

def __repr__(self):
rowname= ""
for i in range(self.rows):
rowname += 'Row %s = %s\n' %(i+1, self.matrix[i])

return rowname
sentence="hello world"
m=Matrix(len(sentence),4)
print(m)

提前致谢

最佳答案

好吧,我不完全理解你的问题,但我认为你的要点是你想一次设置整行,而不是一个字母一个字母地设置。

假设您想要 set_Guess 执行的操作是将第 row 行设置为 Guess,那么您可以将其更改为类似的内容这个:

def set_Guess(self, row, Guess):
self.matrix[row][:] = Guess
def get_Guess(self, row):
return self.matrix[row][:]

所以,基本上:

def set_Guess(matrix, row, Guess):
matrix[row][:] = Guess
return matrix

def get_Guess(matrix, row):
return matrix[row][:]

sentence = "hello world"
rows = 4
cols = len(sentence)
matrix = [['0'] * cols for row in range(rows)]

set_Guess(matrix, 1, "hello world")

for rn, row in enumerate(matrix):
print('Row {rnum:d} = [{rvals}]'.format(rnum=rn+1, rvals=', '.join(row)))

这将返回您正在寻找的内容:

> python testmatrix.py
Row 1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Row 2 = [h, e, l, l, o, , w, o, r, l, d]
Row 3 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Row 4 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

也就是说,我怀疑对于您的特定应用程序,您没有以正确的方式处理事情。我建议您可以将您的申请转至Code Review获得更多设计帮助。

关于python - 如何在 Python 中创建包含不同变量的列表(矩阵)列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28785610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com