목록 목록에서 nlargest 요소를 얻기 위해 heapq를 사용하고 있습니다. 내가 작성한 프로그램은 아래와 같습니다.파이썬 목록에서 n 개의 가장 큰 목록을 얻는 방법
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
그냥 상위 20 개 요소 만 넣으면됩니다. 정렬 대신에 힙 사용을 생각했습니다. 내가 얻는 오류는 다음과 같습니다.
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
오류가 발생하는 이유와 해결 방법을 알 수 있습니까? heapq를 사용하는 속성이 누락되었습니다.
행의 길이는 어떻게 되나요? 그것들은 같은가요? – Kasramvd
예, 크기 4입니다. – WannaBeCoder