简体   繁体   中英

What is causing this for loop to behave strangely?

I'm trying to build a Caesar cipher. Below is a small portion of the decoding portion of the code. Essentially, it takes an input and shifts it (key) spaces to the left in the alphabet.

For some reason, it's returning the answer out of order - 'uulz' instead of 'zulu'. Why is the for loop iterating out of order in this case?

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

working = ['e','z','q','z']

key = 5

for position in working:
    working[working.index(position)] = alphabet[alphabet.index(position)-key]

print(working)

You're updating the same list that you are looping through. Try assigning a new list for the results.

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
working = ['e','z','q','z']
key = 5
new_list=[]
for position in working:
    new_list.append(alphabet[alphabet.index(position)-key])

print(new_list)
['z', 'u', 'l', 'u']

or alternatively, try:

for num, position in enumerate(working):
    working[num] = alphabet[alphabet.index(position)-key]
print(working)

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