[英]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.