TypeError: list indices must be integers
John Machin
sjmachin at lexicon.net
Wed Dec 31 08:55:57 EST 2008
On Dec 31 2008, 3:26 pm, dubux <wx1... at gmail.com> wrote:
> thanks for help everyone. it turned out the function itself worked
> fine.. it was the way i was calling it that was messing everything up.
> i ended up re-doing the whole thing as follows, and it now works
> perfectly.
>
> def news(x,y):
> news_file = '/home/scam/Desktop/www/info/news'
> news = open(news_file, 'r')
> news_list = news.readlines()
> news.close()
> if x == 'date':
> mylist = map(lambda i: news_list[i], filter(lambda i: i%2 == 0, range
> (len(news_list))))
> date = mylist[y].replace("\n","")
> return '<center><p>%s</p></center>\n\n' % (date)
> if x == 'news':
> mylist = map(lambda i: news_list[i], filter(lambda i: i%2 == 1, range
> (len(news_list))))
> news = mylist[y].replace("\n","")
> return '<center><p>%s</p></center>\n<br>\n' % (news)
> else:
> return news_list
>
> news_parse, count, news_list = " ", 0, news('list','list')
> newss = map(lambda i: news_list[i], filter(lambda i: i%2 == 1, range
> (len(news_list))))
> while count < len(newss):
> get_date = news('date', count)
> get_news = news('news', count)
> news_parse = '%s %s %s' % (news_parse, get_date, get_news)
> count = count + 1
Unless I'm sorely mistaken, the whole of the above can be replaced by
something like (untested):
news_file = '/home/scam/Desktop/www/info/news'
news = open(news_file, 'r')
accum = []
for lineno, line in enumerate(news):
accum.append('<center><p>%s</p></center>\n%s\n' % (line.strip(),
('', '<br>')[lineno % 1]))
news_parse = ' '.join(accum)
news.close()
count = (lineno + 1) // 2 # if indeed count is needed
with the virtues of brevity and speed ... if there are N (date, news)
items, your code reads the file 2*N+1 times!!!
How big is N?
More information about the Python-list
mailing list