如何按长度对单词列表进行排序

Kob*_*man 3 python sorting python-2.7

我想根据长度对列表中的单词进行排序。

测试用例是 {'cat','jump','blue','balloon'}

通过此方法运行时,它将按照以下内容打印内容:

{'balloon','jump','blue','balloon'}
Run Code Online (Sandbox Code Playgroud)

我遇到的另一个问题是,我们使用的python类型工作正常,但是当我尝试在Python 3.5.2 shell中运行.py时,出现了错误。

我主要只需要知道我做错了什么,以及我可以做些什么来解决它,以使其起作用。任何帮助表示赞赏!

.py文件可以在这里找到

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
Run Code Online (Sandbox Code Playgroud)

xss*_*han 5

  • print是Python 3.5中的函数,需要用作print(words)在这里了解更多
  • 给定单词列表,可以使用sorted根据字符串的长度对它们进行排序

    sorted(word_list , key = len)