前言:這是一項家庭作業,我不是在尋找完整的答案,只是在正確的方向上微調。我正在編寫一個簡單的加密程序,它將文件的名稱作爲輸入,打開它並用隨機轉移的行重寫它。我已經這樣做了,但我需要以某種方式記錄轉移的行號。我知道我需要寫一個新列表,並在索引+1後添加索引,但我不知道該把它放在哪裏。交換列表中的值並記錄原始索引
from random import *
seed(123)
text_file = input("Enter a name of a text file to mix: ")
f = open(text_file, 'r')
encrypted = open('encrypted.txt', 'w')
index = open('index.txt', 'w')
lines = []
for line in f:
line = line.strip('\n')
lines.append(line)
ll=len(lines)
new_dict = {}
for line in lines:
new_dict[lines.index(line)+1] = line
for i in range (0,ll*3):
random_one = randint(0,ll-1)
random_two = randint(0,ll-1)
temp1 = lines[random_one]
temp2 = lines[random_two]
lines[random_one] = temp2
lines[random_two] = temp1
for line in lines:
encrypted.write(line + "\n")
encrypted.close()
正如你看到的,我也提出,將包含.txt文件作爲1的內容的字典:lineone 2:linetwo。但我不確定是否會更容易使用它,或者只是使用列表來跟蹤它。
編輯:我改變了我的代碼包括:
new_dict[random_one] = temp2
new_dict[random_two] = temp1
new_dict現在打印移位列表的順序正確,但在錯誤的索引。例如,1:line7 2:line11,但我希望索引匹配行號,這樣我就可以將密鑰打印到索引文件中用於解密。例如:7:line7 11:line11任何提示?
你可能有興趣在使用洗牌算法來減少你目前做簿記量。你會發現[Fisher-Yates算法的Knuth實現](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm)很可能適合你的需求。 –
如果'''new_dict'''包含你需要重建文件的信息,並且你已經正確實現了它(它有效),那麼在這一點上它是最簡單的,因爲它完成了。 – wwii
你可能會發現[enumerate](https://docs.python.org/3/library/functions.html#enumerate)對於構造''''new_dict'''很有用:'''對於我,enumerate(行):...''' – wwii