比排序元组提供的更优雅的解决方案?

use*_*285 0 python sorting tuples

我正在研究一个关于元组的噱头问题并最终解决了......但我觉得我的编码真的很难看.有没有pythonic /更简单的方法?基本上,这个问题给你一个元组,你需要对元组进行排序,从同一个元组中删除数字,然后创建这样的输出.

OUTPUT = [this,sentence,should,now,make,sense]

一开始,你有......

t=[(4,'make'),(1,'sentence'),(0,'this'),(3,'now'),(5,'sense'),(2,'should')] 
Run Code Online (Sandbox Code Playgroud)

我的解决方案

t=[(4,'make'),(1,'sentence'),(0,'this'),(3,'now'),(5,'sense'),(2,'should')] 

def makeList(t):
    result = ''
    t.sort()
    for x, y in t:
        result += y +', '
    result = result[:-2]    
    result = ('[' + ', '.join([result]) + ']')
    return result 

OUTPUT: [this, sentence, should, now, make, sense] 
Run Code Online (Sandbox Code Playgroud)

Nik*_* B. 7

这很简单:

sentence = [(4,'make'),(1,'sentence'),(0,'this'),(3,'now'),(5,'sense'),(2,'should')]
print "[%s]" % ', '.join(word for _,word in sorted(sentence))
Run Code Online (Sandbox Code Playgroud)

这里有几点需要注意:

  • 发电机被用作一个参数join.语法与列表推导相同
  • 我们遍历排序的元组列表并_用来表示我们不需要元组的第一个值(数字),而只需要第二个部分(单词)
  • 一个C风格的格式字符串用来与构建最终的字符串[]周围.我们也可以str.format在这里使用,但我认为它看起来更干净(在这个例子中)