如何按照一定的标准对列表进行排序 [英] how to sort list according certain criterion

查看:86
本文介绍了如何按照一定的标准对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有一个列表

list = [['word1', 0.234], ['word2', 0.2], ['word3', 0.5], ['word4', 0,67]]

,我想按重要性对其进行排序.重要性是指该值与0.5相差多远.排序后的列表应为:

and I want to sort it by importance. Importance means how far is the value from 0.5. The list after sorting should be:

list = [['word2', 0.2], ['word1', 0.234], ['word4', 0.67], ['word3', 0,5]]

首先我通过编写基于气泡排序的简单函数解决了它,但是它非常慢.

First I solved it by writing simple function based on bubble sorting but it's very slow.

def most_interesting_words(seznam):
"""sort list i.e. [['word', spamicity], ...], first tokens whose value was furthest from the neutral value of 
for i in range(len(seznam)):
    for j in range(len(seznam)):
        #if dist_from_05(seznam[i][1]) > dist_from_05(seznam[j][1]):
        if abs(0.5 - seznam[i][1]) > abs(0.5 - seznam[j][1]):
            tmp = seznam[i]
            seznam[i] = seznam[j]
            seznam[j] = tmp
return seznam

如何使用sorted()函数解决它?

How it can be solved with sorted() function?

推荐答案

要按与0.5的距离排序,可以使用以下sorted()函数:

To sort by distance from 0.5 you can use the following sorted() function:

my_list = [['word1', 0.234], ['word2', 0.2], ['word3', 0.5], ['word4', 0.67]]
print(sorted(my_list, key=lambda x: abs(0.5 - x[1]), reverse=True))

这将为您提供以下输出:

This would give you the following output:

[['word2', 0.2], ['word1', 0.234], ['word4', 0.67], ['word3', 0.5]]

这篇关于如何按照一定的标准对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆