기본적으로 1'st 색인을 정렬하려고 시도하는 중첩 목록이 있습니다. python howto가하는 방법을 복사했지만, 웹 사이트에서Python sorted() 함수가 정상적으로 작동하지 않습니다.
코드 :
>>> student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
]
>>> sorted(student_tuples, key=lambda student: student[2]) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
내 코드 :
def print_scores(self):
try:
#opening txt and reading data then breaking data into list separated by "-"
f = open(appdata + "scores.txt", "r")
fo = f.read()
f.close()
userlist = fo.split('\n')
sheet_list = []
for user in userlist:
sheet = user.split('-')
if len(sheet) != 2:
continue
sheet_list.append(sheet)
sheet_list.sort(key = lambda ele : ele[1]) #HERE IS THE COPIED PART!
if len(sheet_list) > 20: # only top 20 scores are printed
sheet_list = sheet_list[len(sheet_list) - 21 :len(sheet_list) - 1]
#prints scores in a nice table
print "name score"
for user in sheet_list:
try:
name = user[0]
score = user[1]
size = len(name)
for x in range(0,14):
if x > size - 1:
sys.stdout.write(" ")
else:
sys.stdout.write(name[x])
sys.stdout.write(score + "\n")
except:
print ""
except:
print "no scores to be displayed!"
버그는 결과 인쇄 목록 exac가되는 이유 t는 제대로 작동하고 이해가 안 돼요 txt처럼 정렬 기능이 아무 것도하지 않는 것처럼 txt에있는 것처럼!
예 : txt 파일에
데이터 :
Jerry-1284
Tom-264
Barry-205
omgwtfbbqhaxomgsss-209
Giraffe-1227
인쇄의 새로운 기능 :
Name Score
Giraffe 1227
Jerry 1284
Barry 205
omgstfbbqhaxom209
Tom 264
[프로그래밍의 첫 번째 규칙 : 항상 사용자의 잘못입니다.] (http://www.codinghorror.com/blog/2008/03/the-first-rule- of-programming-its-always-your-fault.html) –
@Brian Roach 그것은 굉장했습니다! – aitchnyu
@aitchnyu - Jeff Atwood는 Stackoverflow의 공동 설립자입니다. 그는 몇 년 동안 훌륭한 블로그 게시물을 만들었습니다. 그건 내 즐겨 찾기 중 하나입니다. –