I use heapq to get the smallest items from a list of lists. The program I wrote is below.
import csv import heapq f = open("E:/output.csv","r") read = csv.reader(f) allrows = [row for row in read] for i in xrange(0,2): print allrows[i] allrows.sort(key=lambda x: x[2]) #this is working properly it=heapq.nlargest(20,enumerate(allrows),key=lambda x:x[2]) #error
I just need the top 20 items. So instead of sorting, I thought about using heap. The error I get is
Traceback (most recent call last): File "D:\eclipse_progs\DaDv\IMDB\Assignment1.py", line 42, in <module> it=heapq.nlargest(2,enumerate(allrows),key=lambda x:x[2]) File "C:\Python27\lib\heapq.py", line 470, in nlargest result = _nlargest(n, it) File "D:\eclipse_progs\DaDv\IMDB\Assignment1.py", line 42, in <lambda> it=heapq.nlargest(2,enumerate(allrows),key=lambda x:x[2]) IndexError: tuple index out of range
Can I find out why I get the error and how to solve it. Is there any property of using heapq that I don't see.
python
Wannabeccoder
source share