基本上我有一個嵌套列表,我試圖通過1'st索引排序 我複製了python howto如何做的方式,但它不'不像是會工作,我不明白爲什麼:從網站Python排序()函數不工作的方式它應該
代碼:
>>> 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 tly好像它是如何在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) – 2012-01-07 06:13:12
@Brian Roach真棒! – aitchnyu 2012-01-07 06:38:53
@aitchnyu - Jeff Atwood是Stackoverflow的聯合創始人。多年來他做了一些很棒的博客文章。這是我的最愛之一。 – 2012-01-07 06:40:12