2012-07-22 158 views
8

我正在打印一些列表,但這些值未排序。基於python中的單個列表對多個列表進行排序

for f, h, u, ue, b, be, p, pe, m, me in zip(filename, human_rating, rating_unigram, percentage_error_unigram, rating_bigram, percentage_error_bigram, rating_pos, percentage_error_pos, machine_rating, percentage_error_machine_rating): 
     print "{:>6s}{:>5.1f}{:>7.2f}{:>8.2f} {:>7.2f} {:>7.2f} {:>7.2f} {:>8.2f} {:>7.2f} {:>8.2f}".format(f,h,u,ue,b,be,p,pe,m,me) 

根據'文件名'中的值排序所有這些列表的最佳方法是什麼?

所以,如果:

filename = ['f3','f1','f2'] 
human_rating = ['1','2','3'] 
etc. 

然後排序將返回:

filename = ['f1','f2','f3'] 
human_rating = ['2','3','1'] 
etc. 

回答

8

我會壓縮然後進行排序:

zipped = zip(filename, human_rating, …) 
zipped.sort() 
for row in zipped: 
    print "{:>6s}{:>5.1f}…".format(*row) 

如果你真的想要得到的個人名單後面,我會像上面那樣對它們進行排序,然後解壓縮它們:

filename, human_rating, … = zip(*zipped) 
+0

的Python 3注:拉鍊在Python 3返回一個迭代器,使用列表,查看其內容, ' zipped = list(zip(filename,human_rating,...))' – 2017-08-24 13:53:21

0

zip返回可以按其第一個值排序的元組列表。所以:

for ... in sorted(zip(...)): 
    print " ... " 
2

如何:zip成元組的列表,排序元組的列表,然後選擇「解壓」?

l = zip(filename, human_rating, ...) 
l.sort() 
# 'unzip' 
filename, human_rating ... = zip(*l) 

或者在同一行:

filename, human_rating, ... = zip(*sorted(zip(filename, human_rating, ...))) 

採樣運行:

foo = ["c", "b", "a"] 
bar = [1, 2, 3] 
foo, bar = zip(*sorted(zip(foo, bar))) 
print foo, "|", bar # prints ('a', 'b', 'c') | (3, 2, 1) 
相關問題