简体   繁体   中英

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 = ['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

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:

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: 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM