如何按长度对单词列表进行排序 [英] How to sort a list of words by length
问题描述
我想根据长度对列表中的单词进行排序.
I want to sort words in a list based on length.
测试用例为{'cat','jump','blue','balloon'}
通过此方法运行时,它将打印出以下内容:
When run through this method it will print something along the lines of:
{'balloon','jump','blue','balloon'}
我遇到的另一个问题是,我们使用的python类型工作正常,但是当我尝试在Python 3.5.2 shell中运行.py时,就会出现错误.
Another problem I have run into, is that the type of python we were using worked fine, however when I try to run the .py in the Python 3.5.2 shell, it comes up with errors.
我主要只需要知道我做错了什么,以及我可以做些什么来对其进行修复以使其起作用.感谢您的帮助!
I mainly just need to know what I did wrong, and what I can do to fix it so that it works. Any help is appreciated!
.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
推荐答案
-
print
是Python 3.5中的一个函数,需要用作print(words)
.在此处 了解更多信息
-
给出了一个单词列表,可使用已排序:
print
is a function in Python 3.5 and needs to be used asprint(words)
. Read more about it hereGiven a list of words this can be used to sort them according to length of string using sorted:
sorted(word_list , key = len)
这篇关于如何按长度对单词列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!