我想找个人帮我理解几行代码

2024-09-26 04:59:18 发布

您现在位置:Python中文网/ 问答频道 /正文

这里的任何一个人能不能请用这个代码举例,如果可能的话,这个代码在做什么?你知道吗

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

反向的意思是什么?反向是什么?我确实明白人们用什么方法来表示,而不是用反向来表示什么


Tags: 代码inforbylendefressort
3条回答

按长度对单词排序

w = ["abcd", "za", "wyya", "dssffgdg"]
print sort_by_length(w);

http://ideone.com/jRzatV

它返回一个单词列表,从最长到最短排序,然后从z到a

你也可以做同样的事

def sort_by_length(words):
    return sorted(words, key=lambda w: (len(w), w), reverse=True)

从最长到最短,从a到z排序可能更有意义

def sort_by_length(words):
    return sorted(words, key=lambda w: (-len(w), w))
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

相关问题 更多 >