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

时间:2017-04-04 04:11:21

标签: python python-2.7 sorting

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

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

当运行此方法时,它将按以下方式打印:

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

我遇到的另一个问题是我们使用的python类型工作正常,但是当我尝试在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

2 个答案:

答案 0 :(得分:4)

  • import { Injectable } from '@angular/core'; import { AuthService } from './auth.service'; import { Http, Headers, RequestOptions, Response } from '@angular/http'; @Injectable() export class UserService { BASE_URL: string = 'http://localhost:3000'; constructor( private http: Http, private authService: AuthService ) { } get(id) { let headers = new Headers({ 'Authorization': 'JWT ' + this.authService.token }); let options = new RequestOptions({ headers: headers }); return this.http.get(this.BASE_URL + '/users/' + id, options) .map((res) => res.json()); } 是Python 3.5中的一个函数,需要用作print。详细了解here
  • 给定一个单词列表,可以使用sorted根据字符串的长度对它们进行排序:

    print(words)

答案 1 :(得分:1)

试试这个。它将根据字符串的长度按升序对列表进行排序

list_name.sort(key=len)

按降序排列,

list_name.sort(key=len,reverse=True)