Reputation: 21
I recently started to use python and i am still newbie with many things of the language. This piece of code should print a serie rows (Ex.:[47.815, 47.54, 48.065, 57.45]) that i take as imput from several text files (called 2t1,...,2t19,3t1,...,3t19) and the name of the file after it's over. Every file has 80 elements that must be saved (for a total of ~12000 elements, ~80 rows for each file, 4 elements each row)
for i in range(2,3):
for j in range(1,19):
#Open a text file and convert the row content to float:
for line in open('[Path]/%dt%d.txt' % (i,j)):
# Ignore comments:
if not line.startswith('#'):
# Got a valid data line:
row[i][j] = [float(item) for item in line.split()]
print (row[i][j])
print (' %dt%d \n' %(i,j))
It is able to do what i ask it, but just until 2t5 and then it is shown this message:
Traceback (most recent call last):
File "< tmp 1>", line 8, in < module>
row[i][j] = [float(item) for item in line.split()]
IndexError: list assignment index out of range
I can't really figure out what's the problem, i guess the list isn't filled to it's max (i read online that it has 500.000.000 spaces), and i can't see what may be wrong . That error appears when the list you are working on is empty, but i doublechecked and there is every file, but i also tryed with
row[i][j].append(float(item) for item in line.split())
(that is the solution for the most common mistakes) and it returns me a really long list of this:
< generator object < genexpr> at 0x000000000XXXXXXX>
(Where the X are different numbers) ending then with the same error.
P.s. If you need the data i'm working on just ask and i'll upload it.
Upvotes: 1
Views: 19757
Reputation: 5588
It seems like your problem is pretty straightforward. You probably have a list named row
and you're trying to assign values to non-existent indices
>>> row = []
>>> row[0] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
If however you appended a new list into the row list like I think you want to do
>>> row = []
>>> row.append([1, 2, 3, 4])
>>> row
[[1, 2, 3, 4]]
>>> row[0][0]
1
This would work fine. If you're trying to triple nest things
>>> row = []
>>> row.append([[1,2,3,4]])
>>> row
[[[1, 2, 3, 4]]]
>>> row[0].append([-1, -2, -3, -4])
>>> row
[[[1, 2, 3, 4], [-1, -2, -3, -4]]]
You can use the same syntax
Upvotes: 3