在列表中交换值并记录原始索引



前言:这是一个家庭作业,我不是在寻找一个完整的答案,只是朝着正确的方向稍微推动一下。 我正在编写一个简单的加密程序,它将以文件名作为输入,打开它并使用随机移动的行重写它。 我已经这样做了,但我需要以某种方式跟踪移动的行号。 我知道我需要写一个新列表并在它们更改时附加索引 + 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:7行 11:11行 有什么提示吗?

您实际上不需要保存随机行的顺序。您可以在需要时使用最初使用的相同随机种子简单地重新创建它。下面的代码应该给你一些想法。

import random
random.seed(123)
# Create a simple list of strings
a = list('abcdefgh')
print(a)
# Generate a shuffled list of indices
indices = list(range(len(a)))
random.shuffle(indices)
# Shuffle a into b
b = []
for i in indices:
b.append(a[i])
print(b)
# Unshuffle b into c
c = [None] * len(b)
for i, v in zip(indices, b):
c[i] = v
print(c)

输出

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
['b', 'e', 'f', 'g', 'd', 'h', 'c', 'a']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

只需用indeces 洗牌一个 numpy 数组并洗牌即可。因此,您可以保存索引以供以后使用。

import numpy as np
indices = np.arange(5)
np.random.shuffle(indices)
print(indices)

不带数字的版本:

from random import shuffle
indices = list(range(5))
shuffle(indices)

最新更新