简体   繁体   中英

How do I loop through the same lists multiple times?

Please bear with me, I have been using Python for only 2 weeks.

I am writing a small project which includes using a user defined key to scramble a text file (string).

Example:

String = "Monty"
Key = 1232

The first thing I do is split it into letters so they become:

['m','o','n','t','y'] (all letters are lowercased)

['1','2','3','2']

Easy enough so far for me. I also have a list which has all english letters and numbers from 0-9.

Now, the scrambling part looks like this:

def encrypt0r(textList,keyList,letterList): #Encrypting the string using the key
    encryptedList = []
    encryptedStr = ""

    for character in textList:
        if character in letterList:
            tempIndex = letterList.index(character) + 1 #THE 1 IS A PLACEHOLDER
            encryptedList.append(letterList[tempIndex])

        else:
            encryptedList.append(character) 
    encryptedStr = "".join(encryptedList)
    return encryptedStr

where the 3 lists are my list of letters, the list of 4 digits and list of all english letters and nums respectively.

The output of monty should be like so:

nqqvz

because:

index of m + 1 = n

index of o + 2 = q

index of n + 3 = q

index of t + 2 = v

index of y + 1 = z **Note how when the keyList is already over, it goes back to the start of the keyList. How can I make it go through the list then once it does so once, go through it again.

If there is a faster way with the steps, I would love to hear it. I keep getting these godsent images of [0::4] - [3::4] in my head but I have no idea how to implement it.

My second problem is similar to my first:

The placeholder in the above code is just to check if my program actually works without the user defined key. And it does, unless you tell it to go past the letterlist. The list ends at [......,'8','9'], so 8 + 1 will be scrambled as 9 but I want 9 + 1 to go BACK to the start of this same list back and scramble the 9 as an "a". I've been scouring the internet for 2 days and i finally caved in to posting here.

Thanks in advance for your help. Just asking you guys to keep the jargon/lingo a little more understandable to whats essentially a script kiddie (me), and if you have a solution, explain to me how it works so that I may learn and use it in a future project!

Part 1

Every letter in the input is coupled to an element in the key list. This means this is a job for zip (izip in python 2):

for character, key in zip(textList, keyList):
    # processing

The problem is that if keyList is shorter than textList , it will stop at the end of keyList . However, there is a nice tool in itertools just for this: itertools.cycle :

for character, key in zip(textList, itertools.cycle(keyList)):
    # processing

Part 2

If the index to get is greater than the length of the letterList, you want to start again from the front. This means the index to get is the modulo of the index and the length of the list:

encryptedList.append(letterList[tempIndex % len(letterList)])

Looking up an index has worst case complexity O(n), meaning it will look at every element in the list, if the wanted element is at the end. To make these lookups a lot faster, build a dictionary of the keys before you start and look up the indices in that (O(1) complexity):

lettermap = {letter: i for i, letter in enumerate(letterList)}

And then in your loop:

if character in lettermap:
    tempIndex = lettermap[character]

All together

def encrypt0r(text, keys, letters):
    encrypted = []
    lettermap = {letter: i for i, letter in enumerate(letters)}

    for character, key in zip(text, itertools.cycle(keys)):
        if character in lettermap:
            new_index = lettermap[character] + key
            encrypted.append(letters[new_index%len(letters)])
        else:
            encrypted.append(character)
    return "".join(encrypted)

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