对前十个结果进行排序 [英] Sort the top ten results
问题描述
我得到一个列表,其中我以下列方式保存结果
城市百分比孟买 98.30伦敦 23.23阿格拉 12.22.....
列表结构为 [["Mumbai",98.30],["London",23.23]..]
我正在以列表的形式保存这些记录.我需要将列表排序为 top_10 记录.即使我也得到了城市,也可以.
我正在尝试使用以下逻辑,但无法提供准确的数据
if(条件):如果 b 不在 top_ten 中:top_ten.append(b)top_ten.remove(tmp)
也欢迎任何其他解决方案.
编辑 1
for a in sc_percentage:打印一个
我得到的清单
(, 100.0)(<ServiceCenter: DELHI-DLE>, 75.0)(<服务中心:DELHI-DLN>, 90.909090909090907)(<服务中心:DELHI-DLS>, 83.333333333333343)(<服务中心:DELHI-DLW>, 92.307692307692307)
先对列表进行排序再切片:
<预><代码>>>>lis = [['孟买', 98.3], ['伦敦', 23.23], ['阿格拉', 12.22]]>>>print sorted(lis, key = lambda x : x[1], reverse = True)[:10] #[:10] 返回前十项[['孟买',98.3],['伦敦',23.23],['阿格拉',12.22]]要从该文件以列表形式获取数据,请使用:
with open('abc') as f:next(f) #跳过标题lis = [[city,float(val)] for city, val in(line.split() for line in f)]打印列表#[['孟买', 98.3], ['伦敦', 23.23], ['阿格拉', 12.22]]
更新:
new_lis = sorted(sc_percentage, key = lambda x : x[1], reverse = True)[:10]对于 new_lis 中的项目:打印项目
sorted
返回一个新的排序列表,因为我们需要根据每个元素的第二项对列表进行排序,因此我们使用了 key
参数.
key = lambda x : x[1]
表示使用每个项目的索引 1(即 100.0、75.0 等)上的值进行比较.
reverse= True
用于反向排序.
I am getting a list in which I am saving the results in the following way
City Percentage
Mumbai 98.30
London 23.23
Agra 12.22
.....
List structure is [["Mumbai",98.30],["London",23.23]..]
I am saving this records in form of a list.I need the list to be sort top_ten records.Even if I get cities also, it would be fine.
I am trying to use the following logic, but it fails for to provide accurate data
if (condition):
if b not in top_ten:
top_ten.append(b)
top_ten.remove(tmp)
Any other solution,approach is also welcome.
EDIT 1
for a in sc_percentage:
print a
List I am getting
(<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)
Sort the list first and then slice it:
>>> 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]]
To get data in list form from that file use this:
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]]
Update:
new_lis = sorted(sc_percentage, key = lambda x : x[1], reverse = True)[:10]
for item in new_lis:
print item
sorted
returns a new sorted list, as we need to sort the list based on the second item of each element so we used the key
parameter.
key = lambda x : x[1]
means use the value on the index 1(i.e 100.0, 75.0 etc) of each item for comparison.
reverse= True
is used for reverse sorting.
这篇关于对前十个结果进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!