gpt4 book ai didi

python - 按键对列表进行排序

转载 作者:太空宇宙 更新时间:2023-11-03 11:03:09 26 4
gpt4 key购买 nike

目前正在研究换位问题。到目前为止,我所拥有的是用户输入一条消息,该消息被加密到一个列表中,如下所示:

 ['BC', 'DE', 'DE', 'DA', 'FD', 'DD', 'BE', 'FE', 'DA', 'EA', 'FE', 'BC']

对于密码的下一阶段,我所拥有的是将其放入一个表中,并使用用户输入的 key 。因此,如果用户输入“CODE”,它会输出:

2: Enter the keyword for final encryption: code
C O D E
['B', 'C', 'D', 'E']
['D', 'E', 'D', 'A']
['F', 'D', 'D', 'D']
['B', 'E', 'F', 'E']
['D', 'A', 'E', 'A']
['F', 'E', 'B', 'C']

下一阶段是获取每一列的每个值并打印与其字母列对应的值。所以我的预期输出是:

   C    D    E    O 
['B', 'D', 'E', 'C']
['D', 'D', 'A', 'E']
['F', 'D', 'D', 'D']
['B', 'F', 'E', 'E']
['D', 'E', 'A', 'A']
['F', 'B', 'C', 'E']

我遇到的问题是试图知道如何将每个值放在相应的列中并打印它们。

这是我目前所拥有的:

def encodeFinalCipher():
matrix2 = []
# Convert keyword to upper case
key = list(keyword.upper())

# Convert firstEncryption to a string
firstEncryptionString = ''.join(str(x) for x in firstEncryption)

# Print the first table that will show the firstEncryption and the keyword above it
keywordList = list(firstEncryptionString)
for x in range(0,len(keywordList),len(keyword)):
matrix2.append(list(keywordList[x:x+len(keyword)]))

# Print the un-ordered matrix to the screen
print (' %s' % ' '.join(map(str, key)))
for letters in matrix2:
print (letters)

unOrderedMatrix = [[matrix2[i][j] for i in range(len(matrix2))] for j in range(len(matrix2[0]))]
for index, item in enumerate (unOrderedMatrix):
print("\n",index, item)

index = sorted(key)
print(index)

我得到排序键的输出:

['A', 'K', 'M', 'R']

我想知道的是如何将这个排序键应用于它们所代表的值?我知道我可以通过这样做获得第一列:

print(unOrderedMatrix[0])

这让我得到第一列的列表。

任何帮助将不胜感激。 Python 完全初学者

最佳答案

msg = ['BC', 'DE', 'DE', 'DA', 'FD', 'DD', 'BE', 'FE', 'DA', 'EA', 'FE', 'BC', '12']
key = 'CODE'
# 'flatten' the message
msg = ''.join(msg)
key_length = len(key)
#create a dictionary with the letters of the key as the keys
#use a slice to create the values
columns = {k:msg[i::key_length] for i, k in enumerate(key)}
print columns
# sort the columns on the key letters
columns = sorted(columns.items())
print columns
# separate the key from the columnar data
header, data = zip(*columns)
print header
# transpose and print
for thing in zip(*data):
print thing

>>>
{'C': 'BDFBDF1', 'E': 'EADEAC', 'D': 'DDDFEB', 'O': 'CEDEAE2'}
[('C', 'BDFBDF1'), ('D', 'DDDFEB'), ('E', 'EADEAC'), ('O', 'CEDEAE2')]
('C', 'D', 'E', 'O')
('B', 'D', 'E', 'C')
('D', 'D', 'A', 'E')
('F', 'D', 'D', 'D')
('B', 'F', 'E', 'E')
('D', 'E', 'A', 'A')
('F', 'B', 'C', 'E')
>>>

关于python - 按键对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27343683/

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