还有比元组排序更优雅的解决方案吗?

2024-05-29 10:00:27 发布

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

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

输出=[这个,句子,应该,现在,有意义]

一开始,你有。。。你知道吗

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

我的解决方案

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] 

Tags: 方法代码make排序数字resultthisnow
2条回答

替代Niklas Baumstark正确答案:

>>> sentence = [(4,'make'),(1,'sentence'),(0,'this'),\
... (3,'now'),(5,'sense'),(2,'should')]
>>> [w for t,w in sorted(sentence)]
['this', 'sentence', 'should', 'now', 'make', 'sense']

(如果你真的想要一个列表而不是一个看起来像列表的字符串…)

这很简单:

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

这里有几点需要注意:

  • generator用作join的参数。语法与list comprehensions相同
  • 我们遍历元组的排序列表,并使用_表示我们不需要元组的第一个值(数字),而只需要第二个部分(单词)
  • 一个C-style format string用于构建最后一个字符串,其周围有[]。我们也可以在这里使用^{},但我认为这样看起来更干净(在这个例子中)

相关问题 更多 >

    热门问题