On 9/3/2009 11:01 AM William Witteman said...
I am trying to create a CSV file of sorted similar lists, arranged so
that differences are easily compared in a spreadsheet. I am
encountering the following error, however:
IndexError: list assignment index out of range
On the indicated line below. I understand the error, but I don't
understand why I am getting it. Can anyone shed some light on this?
Thanks.
#!/usr/bin/python
"""
Take a collection of lists, combine them into one list, deleting duplicates.
Sort the list and use it as the leftmost column of a table. Then put each
lists contents into the table, one per column, with the elements aligned
with the leftmost (index) column.
"""
import os, sys, csv
def cmpss(filename,*sslists):
"""Write a CSV file from the collection of lists."""
if os.path.exists(filename):
print("%s exists: please choose another filename." % filename)
sys.exit(1)
else:
try:
fn = csv.writer(open(filename, "w"))
except IOError:
print("There is a problem opening the requested file. Sorry.")
sys.exit(1)
termdict = {}
for sslist in sslists:
for term in sslist:
termdict[term] = ""
termlist = termdict.keys()
termlist.sort()
sortedtermdict = {}
number_of_commas = 1 - len(sslists)
for term in termlist:
sortedtermdict[term] = ["" for x in range(number_of_commas)]
for sslist in sslists:
counter = 0
for term in sslist:
# The line below is where my program barfs.
sortedtermdict[term][counter] = term
counter = counter + 1
This increases counter once for each term in sslist, but
sortedtermdict[term]'s length is a function of the number_of_commas, so
when termlist if longer then number_of_commas, you'd get the error.
HTH,
Emile
for row in sortedtermdict:
fn.writerow(row)
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor