我有以下程序;
import string
import random
randomgrid = []
codewordgrid = []
codedmessage = []
letters = "ABCDEF"
markletters = "MARK"
message = input("<<<ENTER MESSAGE TO BE ENCODED>>>\n").upper().replace(' ', '')
print ('<<<MESSAGE>>>\n', message)
newlist = list(string.ascii_uppercase + string.digits)
random.shuffle(newlist)
print ('<<<ORIGINAL RANDOM GRID>>>')
for x in range(0,len(newlist),6):
randomgrid.append(list(newlist[x:x+6]))
for letter in message:
for y, vector in enumerate(randomgrid):
for s, member in enumerate(vector):
if letter == member:
codedmessage.append([letters[s], letters[y]])
for item in randomgrid: print(item)
for u in range(0,len(newlist),4):
codewordgrid.append(codedmessage)
print ('<<<CODED MESSAGE>>>\n', codedmessage)
print ('<<<CODEWORD GRID>>>', codewordgrid)
for item in codewordgrid: print(item)
到目前为止一切正常,除了我有一个问题。当打印编码字网格时,它会一次又一次地重复。我想限制代码字网格的大小,以便使用代码字MARK(在标记中)填充4x4网格,而不是一遍又一遍地重复,我不确定如何做到这一点,所以请帮助。
实际输出:
<<<CODEWORD GRID>>> [[['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B']], [['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B']], [['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B']], [['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B']], [['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B']], [['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B']], [['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B']], [['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B']], [['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B']]]
[['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B']]
[['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B']]
[['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B']]
[['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B']]
[['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B']]
[['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B']]
[['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B']]
[['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B']]
[['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B'], ['F', 'B']]
实际上它应该使用代码字“Mark”
拟合到4x4网格中由于
答案 0 :(得分:1)
创建codewordgrid
时:
for u in range(0,len(newlist),4):
codewordgrid.append(codedmessage)
您以len(wordlist) == 36
:4
为步骤迭代[0, 4, 8, 12, 16, 20, 24, 28, 32]
。这会为您提供8行,每行包含codedmessage
。
如果你想用markletters
4次填充它,就这样做:
codewordgrid = [list(markletters) for _ in range(4)]
得到
codewordgrid = [['M', 'A', 'R', 'K'],
['M', 'A', 'R', 'K'],
['M', 'A', 'R', 'K'],
['M', 'A', 'R', 'K']]