|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
||||
|
||||
|
Creating a list of tuples
I am trying to populate a list ot tuples on the fly from a file but keep running into these errors:
Code:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "forum.py", line 84, in getPosts
posts[0] = [(details[0],(details[1],details[2],details[3]),post)]
IndexError: list assignment index out of range
Here is and simplified example of what i am trying to do: Code:
def getDetails(path, id):
"Returns a list of user details in file "
f = open(path + id + ".info", "r")
index = 0
posts = []
line = f.readline()
while line != "":
line = f.readline()
details = string.split(line[:-1], ",")
posts[index] = [(details[0],(details[1],details[2],details[3]),details[4])]
index += 1
f.close()
return posts
Can somebody help I seem to be stuck |
|
#2
|
|||
|
|||
|
Unlike some languages, Python does not automatically extend lists when you assign values past the end. You need to use the append method instead, i.e.
Code:
posts.append([(details[0],(details[1],details[2],details[3]),details[4])]) BTW, if the original data is in CSV (comma separated variables) format then you could use the new csv module to parse it. This will correctly handle commas inside quoted strings. Dave - The Developers' Coach |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > Creating a list of tuples |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|