Python Forum
Extracting elements in a list to form a message using for loop - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Extracting elements in a list to form a message using for loop (/thread-22026.html)



Extracting elements in a list to form a message using for loop - Tony04 - Oct-25-2019

Hello, I'm trying to make a function that will extract letters from a text document to reveal a secret message. I'm stuck at the at the for loop. It says "list object cannot be interpreted as an integer".
def decodefile():
        fr = open("sentences.txt")
        line = fr.readline()    
        
        codeKey = [[0, 1, 2, 4, 7, 14], [6], [1, 16], [7,8], [14,18]]
        while (line) :
            listLine = [ch for ch in line] 
            for x in range(0, len(listLine), codeKey):
                print(codeKey)

            line = fr.readline()
            
        fr.close
decodefile()
Here is the text if it matters.

They like apples.
I enjoy pears.
Time for breakfast.
Serve the oatmeal please.
Leave a tip for the waiter.


RE: Extracting elements in a list to form a message using for loop - nilamo - Oct-25-2019

1) You didn't close your file. In order to easily avoid that sort of mistake, use a with-block:
with open("sentences.txt") as fr:
    for line in fr:
        # do something with the line
2) The third argument to range() is the step. So range(0, 10, 2) == [0, 2, 4, 6, 8]
codeKey is a list, not an int, so it doesn't make sense to be used there.


RE: Extracting elements in a list to form a message using for loop - ichabod801 - Oct-25-2019

Each code key is associated with a particular line. For each line, you need to get the matching code key. You do this with for line, indexes in zip(fr, codeKey):.