0

I'm trying to design a function for encryption that shuffles an array in a custom order using a key as shown below:

arr = ["a","b","c","d","e"]
key = [0,1,4,3,2]
arr2 = arr 
for i in range(len(arr)):
    arr[i]= arr2[key[i]]

print(arr)

problem is, at the moment, the arr2 (which i made as a reference point for the program) changes every time arr changes. Does anyone know how to fix this?

1 Answers1

0

If I've understood the question correctly, you'd like to sort the array in the index order 0,1,4,3,2 compared to the original order of 0,1,2,3,4.

If this is the case, you can use a list comprehension to iterate through the key list and create a new list:

arr = ["a","b","c","d","e"]
key = [0,1,4,3,2]
sorted_by_key_array = [arr[index] for index in key]
print(sorted_by_key_array) # Outputs: ['a', 'b', 'e', 'd', 'c']
Sam
  • 773
  • 4
  • 13
  • Thank you, could you explain how the part in line 3 works, "[arr[index] for index in key]" what does that do? thanks – yipjones2 Dec 14 '21 at 17:09
  • Of course, it's called a list comprehension. An example would be: test_list = [integer for integer in range(10)] This will provide a list of all integers from 0-9. In this case, lets just start with the loop. index for index in key is a list of your keys, which correspond to the desired index. So what needs to be done is for each of the keys, you need to grab the desired element from the list by indexing it: arr[index]. – Sam Dec 14 '21 at 17:19