2017-04-04 188 views
2

我想基於長度對列表中的單詞進行排序。如何按長度對單詞列表進行排序

測試用例{'cat','jump','blue','balloon'}

當通過這種方法運行將打印沿着線的東西:我遇到了

{'balloon','jump','blue','balloon'} 

的另一個問題,就是蟒蛇的類型,我們用工作得很好,但是當我嘗試在Python 3.5.2 shell中運行.py時,它出現了錯誤。

我主要只需要知道我做錯了什麼,以及我能做些什麼來修復它,以便它能夠正常工作。任何幫助表示讚賞!

的.py文件可以發現here:

def wordSort(): 
    words = [] 
    minimum = 'NaN' 
    index = 0 
    x = 0  
    y = 0  
    z = 1 
    #How many words to be entered 
    length = input('How many words would you like to enter? ') 
    #Put words in the number of times you entered previously  
    while not z >= length + 1: 
     words.append(raw_input('Enter word #' + str(z) + ': ')) 
     z += 1 
    while x < length: 
     minimum = words[x] 
     #Goes through the list and finds a smaller word 
     while y < length: 
      if len(words[y]) < len(minimum): 
       minimum = words[y] 
       index = y 
      y += 1 
     words[index] = words[x] 
     words[x] = minimum 
     x += 1 
    print words 
+1

的可能的複製[如何排序對象的列表,基於對象的屬性? ](http://stackoverflow.com/questions/403421/how-to-sort-a-list-of-objects-based-on-an-attribute-of-the-objects) – congusbongus

+1

這是python 2.x(推測是2.7)的代碼。它需要在python 2.x下運行或者爲python 3進行調整。 –

回答

3
  • print是在Python 3.5的函數,並且需要被用作print(words)。瞭解更多關於它here
  • 鑑於可用於根據使用sorted的字符串的長度對它們進行排序的話這個列表:

    sorted(word_list , key = len)

+0

甚至更​​好:'sorted(word_list,key = len)' – hallazzang

+0

@hallazzang是的,那更好。添加到代碼中。 –

0

試試這個。它將基於升序

list_name.sort(key=len) 

降序排序字符串的長度的列表進行排序,

list_name.sort(key=len,reverse=True) 
相關問題