我正在打印一些列表,但值没有排序。
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'中的值对所有这些列表进行排序的最佳方法是什么?
所以如果:
filename = ['f3','f1','f2']
human_rating = ['1','2','3']
etc.
然后排序将返回:
filename = ['f1','f2','f3']
human_rating = ['2','3','1']
etc.
答案 0 :(得分:12)
我会拉链然后排序:
zipped = zip(filename, human_rating, …)
zipped.sort()
for row in zipped:
print "{:>6s}{:>5.1f}…".format(*row)
如果你真的想要收回个人名单,我会按照上面的方式对它们进行排序,然后解压缩它们:
filename, human_rating, … = zip(*zipped)
答案 1 :(得分: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)
答案 2 :(得分:0)
zip
返回一个元组列表,您可以按它们的第一个值进行排序。所以:
for ... in sorted(zip( ... )):
print " ... "