2012-01-07 42 views
-1

基本上我有一個嵌套列表,我試圖通過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 
+5

[編程的第一條規則:總是您的錯](http://www.codinghorror.com/blog/2008/03/the-first-rule- of-programming-its-always-your-fault.html) – 2012-01-07 06:13:12

+0

@Brian Roach真棒! – aitchnyu 2012-01-07 06:38:53

+0

@aitchnyu - Jeff Atwood是Stackoverflow的聯合創始人。多年來他做了一些很棒的博客文章。這是我的最愛之一。 – 2012-01-07 06:40:12

回答

11

sorted返回一個新的列表。如果您想修改現有列表,請使用

sheet_list.sort(key = lambda ele : ele[1]) 
+0

仍然不能完全工作,現在的名單是長頸鹿,傑裏,巴里,omgw和湯姆。它應該是傑裏,長頸鹿,湯姆,omg,巴里。 – joseph 2012-01-07 06:13:42

+2

@joseph:工作表條目是字符串。它按「按字母順序」排序,而不是按數字的值排序。試試key = lambda ele:float(ele [1]),或者將它們預先轉換爲數字。 – DSM 2012-01-07 06:18:30

相關問題