how to access python lists made with a for loop(reading data from a file)

947 views python
4

i have made several arrays using a for loop by splitting lines from a text file. however, i do not know how to access the individual elements that these lists hold. i would prefer if someone showed me how to combine these arrays so the elements inside of them would be easier to access.

file2 = open('text_file.txt','r')
    for line in file2:
        words = line.split()
        words.remove(words[0])
        print(words)

Right now, that prints out this:

['CP', '0.50', '96']
['HR', '1.00', '93']
['HR', '1.00', '85']
['HR', '1.00', '99']
['CP', '0.75', '100']
['CP', '1.00', '94']
['HR', '1.00', '88']
['CP', '1.00', '92']

as you can see, it shows 8 separate lists. When I try to access the data stored in these arrays, using

words[0]
words[1]

or

words[2]

inside of the for loop, i get many values instead of just 1. these arrays have no names, so how can one access each individual number or string from these arrays. for example, when i try:

print(words[0])

i get the following:

CP
HR
HR
HR
CP
CP
HR
CP

however, when i do:

print(words[0])

i want to have this as the result:

CP

answered question

3 Answers

12

"inside of the for loop, i get many values instead of just 1"

of course you will, it is a loop, and the loop will run several times hence the many values. what you need is to create another list of lists where you store your words and then access them from outside the loop:

file2 = open('text_file.txt','r')
lines = []
for line in file2:
    words = line.split()
    words.remove(words[0])
    lines.append(words)
print(lines[0][0]) # to print CP from the first line in the document

posted this
1

Since it appears that you only want to read the 1st line of the file, use

line=file2.readline()
words = line.split()
print(words[1])

posted this
1

try accessing each array this way

words = [['CP', '0.50', '96'],
['HR', '1.00', '93'],
['HR', '1.00', '85'],
['HR', '1.00', '99'],
['CP', '0.75', '100'],
['CP', '1.00', '94'],
['HR', '1.00', '88'],
['CP', '1.00', '92']]

[x[0] for x in words]

posted this

Have an answer?

JD

Please login first before posting an answer.