使用Python中的列按键值排序2d-Array的值

时间:2017-01-12 08:34:59

标签: python arrays sorting

我想按列

对2D-Array进行排序

未排序:

[('222801', '4470'), ('222802', '4753.5')], [('222811', '4468.5'), ('222812', '4742.5')]]

排序

[('222811', '4468.5'), ('222812', '4742.5')], [('222801', '4470'), ('222802', '4753.5')]]

我想之前,它必须转换为元组中值的Float。

我想计算log10然后计算平均行后果。所以将值的结果作为未排序列表中的替换 任何人都可以帮助我吗?

例如 //转换为Float然后计算log10

[(222811, log10(4468.5)), (222812, log10(4742.5))], [(222801, log10(4470)), (222802, log10(4753.5))]]

//然后按行计算平均值

[(222811, log10(4468.5))+log10(4742.5)+log10(4470)+log10(4753.5)/len(arr), (222812, log10(4468.5)+log10(4742.5)+log10(4470)+log10(4753.5)/len(arr)], [(222801, log10(4468.5))+log10(4742.5)+log10(4470)+log10(4753.5)/len(arr), (222802, log10(4468.5))+log10(4742.5)+log10(4470)+log10(4753.5)/len(arr))]]

1 个答案:

答案 0 :(得分:0)

如果要按内部列表中第一个元组的第一个元素排序,可以实现以下内容:

from math import log10

a1 = [[('222801', '4470'), ('222802', '4753.5')], [('222811', '4468.5'), ('222812', '4742.5')]]
mean = sum([log10(float(b)) for a in a1 for b in zip(*a)[1]])/2
mapped_a1 = [[(b[0][0],mean), (b[1][0],mean)] for b in a1]
sorted_a1 = sorted(mapped_a1, key=lambda x: x[0][0], reverse=True)
print sorted_a1

输出:

[[('222811', 7.326745061604671), ('222812', 7.326745061604671)], [('222801', 7.326745061604671), ('222802', 7.326745061604671)]]