[英]how to return a list to its original state in python?
every time a user inputs a message rotorI.append(rotorI.pop(0))
executes on the edited list, i want it to execute on the original list.每次用户输入消息
rotorI.append(rotorI.pop(0))
在编辑列表上执行时,我希望它在原始列表上执行。
rotorI = ['E', 'K', 'M', 'F', 'L', 'G', 'D', 'Q', 'V', 'Z', 'N', 'T','O', 'W','Y','H', 'X', 'U', 'S', 'P', 'A', 'I', 'B', 'R', 'C', 'J']
while True:
msg = input("Enter a msg: ")
for i in range(len(msg)):
rotorI.append(rotorI.pop(0))
print(rotorI)
I want the output to be:我希望输出是:
Enter a msg: hi
['M', 'F', 'L', 'G', 'D', 'Q', 'V', 'Z', 'N', 'T', 'O', 'W', 'Y', 'H', 'X', 'U', 'S', 'P', 'A', 'I', 'B', 'R', 'C', 'J', 'E', 'K']
Enter a msg: hi
['M', 'F', 'L', 'G', 'D', 'Q', 'V', 'Z', 'N', 'T', 'O', 'W', 'Y', 'H', 'X', 'U', 'S', 'P', 'A', 'I', 'B', 'R', 'C', 'J', 'E', 'K']
however this the output i receive:然而这是我收到的输出:
Enter a msg: hi
['M', 'F', 'L', 'G', 'D', 'Q', 'V', 'Z', 'N', 'T', 'O', 'W', 'Y', 'H', 'X', 'U', 'S', 'P', 'A', 'I', 'B', 'R', 'C', 'J', 'E', 'K']
Enter a msg: hi
['L', 'G', 'D', 'Q', 'V', 'Z', 'N', 'T', 'O', 'W', 'Y', 'H', 'X', 'U', 'S', 'P', 'A', 'I', 'B', 'R', 'C', 'J', 'E', 'K', 'M', 'F']
Make a copy of the list at each iteration在每次迭代时制作列表的副本
while True:
msg = input("Enter a msg: ")
newRotor = list(rotorI)
for i in range(len(msg)):
newRotor.append(newRotor.pop(0))
print(newRotor)
Using collections.deque
and string for displaying使用
collections.deque
和 string 进行显示
from collections import deque
rotorI = "EKMFLGDQVZNTOWYHXUSPAIBRCJ"
while True:
msg = input("Enter a msg: ")
newRotor = deque(rotorI)
newRotor.rotate(-len(msg))
print("".join(newRotor))
Enter a msg: hi
MFLGDQVZNTOWYHXUSPAIBRCJEK
Enter a msg: hih
FLGDQVZNTOWYHXUSPAIBRCJEKM
Enter a msg: hihi
LGDQVZNTOWYHXUSPAIBRCJEKMF
Enter a msg: hi
MFLGDQVZNTOWYHXUSPAIBRCJEK
Use copy of your list with using copy()
function:使用 copy
copy()
函数使用列表copy()
:
your_main_list = ['E', 'K', 'M', 'F', 'L', 'G', 'D', 'Q', 'V', 'Z', 'N', 'T','O', 'W','Y','H', 'X', 'U', 'S', 'P', 'A', 'I', 'B', 'R', 'C', 'J']
while True:
msg = input("Enter a msg: ")
list_for_edit = your_main_list.copy()
for i in range(len(msg)):
list_for_edit.append(list_for_edit.pop(0))
print(list_for_edit)
Output is gonna be :输出将是:
Enter a msg: hi
['M', 'F', 'L', 'G', 'D', 'Q', 'V', 'Z', 'N', 'T', 'O', 'W', 'Y',
'H', 'X', 'U', 'S', 'P', 'A', 'I', 'B', 'R', 'C', 'J', 'E', 'K']
Enter a msg: hi
['M', 'F', 'L', 'G', 'D', 'Q', 'V', 'Z', 'N', 'T', 'O', 'W', 'Y',
'H', 'X', 'U', 'S', 'P', 'A', 'I', 'B', 'R', 'C', 'J', 'E', 'K']
Enter a msg:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.