Skip to main content
 首页 » 编程设计

Python根据文件数据的两个字段排序

2024年10月01日1三少

我尝试使用同一问题中接受的解决方案中描述的方法对给定 here 的数据进行排序。我制作了列表列表,而不是集合列表,并尝试使用 sorted 方法进行两次排序。但它没有用。我想要与上面链接中给出的相同的输出。这是我的输出:

[['k3', '9.2603346875', '0.4639390435'], 
['K1', '4.1458078125', '0.5129700421'], 
['k2', '9.5360690625', '0.5481493305'], 
 ['k7', '9.8022878125', '0.562983695'], 
 ['k2', '6.319044375', '0.6469451082'], 
 ['k5', '7.2702040625', '0.6632701035'], 
 ['K1', '8.6394253125', '0.6690271589'], 
 ['K1', '8.025495625', '0.7561548244'], 
 ['k8', '5.44912125', '0.8532092538'], 
 ['k6', '7.73398625', '1.017231759'], 
 ['K1', '6.66228125', '1.0444456163'], 
 ['k4', '10.6868384375', '1.1287761798'], 
 ['k9', '7.5859665625', '1.276779643'], 
 ['K1', '6.48153375', '1.4176140292']] 

这是我的代码:

path = "C:\\Chandresh_WORK\\data\\" 
inpfile = 'demo1.txt' 
mylist=[] 
from operator import itemgetter 
with open(path+inpfile,'r') as fid: 
    for line in fid:       
        myset = list(line.split()) 
        mylist.append(myset) 
 
mylist 
s=sorted(mylist,key=itemgetter(0))      
sorted(s,key=itemgetter(2)) 

请您参考如下方法:

您需要将字符串转换为数字类型以避免字典排序,然后反转第二个排序标准的顺序以使其降序:

s = sorted(mylist,key=lambda x: (x[0], -float(x[2])))  
#                                      ^ invert sort order 

[['K1', '6.48153375', '1.4176140292'], 
 ['K1', '6.66228125', '1.0444456163'], 
 ['K1', '8.025495625', '0.7561548244'], 
 ['K1', '8.6394253125', '0.6690271589'], 
 ['K1', '4.1458078125', '0.5129700421'], 
 ['k2', '6.319044375', '0.6469451082'], 
 ['k2', '9.5360690625', '0.5481493305'], 
 ['k3', '9.2603346875', '0.4639390435'], 
 ['k4', '10.6868384375', '1.1287761798'], 
 ['k5', '7.2702040625', '0.6632701035'], 
 ['k6', '7.73398625', '1.017231759'], 
 ['k7', '9.8022878125', '0.562983695'], 
 ['k8', '5.44912125', '0.8532092538'], 
 ['k9', '7.5859665625', '1.276779643']]