[英]How to sort a list of words by length
我想根据长度对列表中的单词进行排序。
测试案例是{'cat','jump','blue','balloon'}
当运行此方法时,它将打印以下内容:
{'balloon','jump','blue','balloon'}
我遇到的另一个问题是我们使用的python类型工作正常,但是当我尝试在Python 3.5.2 shell中运行.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
试试这个。 它将根据字符串的长度按升序对列表进行排序
list_name.sort(key=len)
按降序排列,
list_name.sort(key=len,reverse=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.