python - 对前十名结果进行排序

标签 python python-2.7 tuples

我得到一个列表,其中我按以下方式保存结果

City Percentage
Mumbai  98.30
London 23.23
Agra    12.22
.....

列表结构是 [["Mumbai",98.30],["London",23.23]..]

我正在以列表的形式保存这些记录。我需要该列表对 top_1 记录进行排序。即使我也得到城市,也没关系。

我正在尝试使用以下逻辑,但它无法提供准确的数据

if (condition):
    if b not in top_ten:
        top_ten.append(b)   
        top_ten.remove(tmp)

也欢迎任何其他解决方案、方法。

编辑 1

for a in sc_percentage:
            print a

我得到的列表

(<ServiceCenter: DELHI-DLC>, 100.0)
(<ServiceCenter: DELHI-DLE>, 75.0)
(<ServiceCenter: DELHI-DLN>, 90.909090909090907)
(<ServiceCenter: DELHI-DLS>, 83.333333333333343)
(<ServiceCenter: DELHI-DLW>, 92.307692307692307)

最佳答案

首先对列表进行排序,然后对其进行切片:

>>> lis = [['Mumbai', 98.3], ['London', 23.23], ['Agra', 12.22]]
>>> print sorted(lis, key = lambda x : x[1], reverse = True)[:10] #[:10] returns first ten items
[['Mumbai', 98.3], ['London', 23.23], ['Agra', 12.22]]

要从该文件中获取列表形式的数据,请使用:

with open('abc') as f:
    next(f)  #skip header 
    lis = [[city,float(val)]  for city, val in( line.split() for line in f)]
    print lis 
    #[['Mumbai', 98.3], ['London', 23.23], ['Agra', 12.22]]  

更新:

new_lis = sorted(sc_percentage, key = lambda x : x[1], reverse = True)[:10]
for item in new_lis:
   print item

sorted 返回一个新的排序列表,因为我们需要根据每个元素的第二项对列表进行排序,所以我们使用了 key 参数。

key = lambda x : x[1] 表示使用每个项目的索引 1 上的值(即 100.0、75.0 等)进行比较。

reverse= True 用于反向排序。

关于python - 对前十名结果进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17295060/

相关文章:

python - 无法使用 Airflow 连接到 Postgres 数据库

python - *_ 以及从 python 中任意长度的可迭代对象中解包元素

c# - ValueTuple.Equals 不返回 true

typescript - 在 typescript 中创建元组数组

python - 从数据样本计算逆 CDF

python - HTTP 错误 403 : Forbidden with exception handling

python - 导出 pandas DataFrame 时如何删除列名行?

python - 安装了 Nose 但不能在命令行上使用

python - 我在 django 中的评论表单不起作用?它既不向数据库发送数据也不显示这些数据?

python - Django 模型可以实例化的最大对象数量?