这里的任何人都可以通过示例请这个代码是否可能这个代码在做什么?
def sort_by_length(words):
t = []
for word in words:
t.append((len(word), word))
t.sort(reverse=True)
res = []
for length, word in t:
res.append(word)
return res
和反向的意思=真正的反向是什么我明白什么是男人的len和追加方法但是回归但他的反向是什么
答案 0 :(得分:0)
它返回一个单词列表,排序最长到最短,然后是z到a。
你可以用
做同样的事情def sort_by_length(words):
return sorted(words, key=lambda w: (len(w), w), reverse=True)
排序最长到最短的a-to-z可能更有意义,这将是
def sort_by_length(words):
return sorted(words, key=lambda w: (-len(w), w))
答案 1 :(得分:0)
def sort_by_length(words):
t = [] # empty list
for word in words:# iterating over given words
t.append((len(word), word)) # appending a word into the list "t" as tupel. e.g word "hello" as (5, "hello")
t.sort(reverse=True) # sorts all tupels in reverse-order
res = []
for length, word in t:
res.append(word) # extracts just the words out of the tupels e.g. (5, "hello") => "hello"
return res # return words ordered
答案 2 :(得分:-1)