2017-04-04 74 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) 
相关问题