2016-08-12 183 views
0

我在正確排序代碼時遇到了問題。排序Python列表

def generateList(attendeeList, criteria, workshoptitle): 
    for i in attendeeList: 
     if(criteria == 'Workshop1'): 
     criteria = 'Workshop B' 
     if(i['session1'] == criteria): 
      temp = [] 
      temp.append((i['lastname'])) 
      temp.sort() 
      print(temp) 

輸出不出來的姓氏排序

['Smith'] 
['Robertson'] 
['Lovelace'] 
['Yu'] 

回答

3

通過每一次循環中,你只是打印在一個單一項目的列表。

temp = [] # empty list 
temp.append((i['lastname'])) # list with one element 
temp.sort() # list is already sorted (since it just has one element) 
print(temp) 

也許你想是這樣的:

def generateList(attendeeList, criteria, workshoptitle): 
    lastnames = [] 
    for i in attendeeList: 
     if(criteria == 'Workshop1'): 
      criteria = 'Workshop B' 
     if(i['session1'] == criteria): 
      lastnames.append(i['lastname']) 
    lastnames.sort() 
    print(lastnames) 

編輯

更地道的Python,而是返回打印出來的清單:

def generate_list(attendee_list, criteria, workshop_title): 
    if criteria == 'Workshop1': 
     criteria = 'Workshop B' 
    return sorted(attendee['lastname'] for attendee in attendee_list 
        if attendee['session1'] == criteria) 
+0

OH是因爲我的溫度是在循環內嗎?那麼它是否每次都重新創建變量並將其放入並重申? – MuthaCluffer

+0

@MuthaCluffer確切地說是 – Anonymous

+0

@MuthaCluffer是的,你每次都將一個新的空列表分配給'temp'。 – Tagc

0

您的代碼沒有做你想做的事。即使您每次打印該項目時,都會在每次迭代時生成一個空列表。

您希望循環之前創建的列表中,在函數體中,然後追加到它,然後對其進行排序,然後如果你想額外打印遍歷它:

def generateList(attendeeList, criteria, workshoptitle): 
    temp = [] 

    if criteria == 'Workshop1': 
     criteria = 'Workshop B' 

    for i in attendeeList: 
     if i['session1'] == criteria : 
      temp.append(i['lastname']) 

    temp.sort() 

    for item in temp: 
     print(item) 

    return temp 

實例中運行IPython:

In [7]: generateList([dict(session1="Workshop B",lastname="test1"), dict(session1="Workshop A", lastname="test2"), dict(session1="Workshop B", lastname="test3")], "Workshop1", ...) 

test1 
test3 

Out[7]: ['test1', 'test3']