如何排序2D清单? [英] How can I sort a 2D list?

查看:70
本文介绍了如何排序2D清单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用类似于下面的示例的2D数字列表,并试图对列进行重新排序:

I'm working with a 2D list of numbers similar to the example below I and am trying to reorder the columns:

D C B A

1 3 2 0

1 3 2 0

1 3 2 0

列表的第一行保留给字母以引用每一列. 如何对列表进行排序,以便将这些列按字母顺序排列以实现以下目的:

The first row of the list is reserved for letters to reference each column. How can I sort this list so that these columns are placed in alphabetical order to achieve the following:

D C B A    A B C D

1 3 2 0    0 2 3 1

1 3 2 0    0 2 3 1

1 3 2 0    0 2 3 1

我找到了使用lambda进行排序的示例,但是没有找到类似的按字符对列进行排序的示例.

I've found examples that make use of lambdas for sorting, but have not found any similar examples that sort columns by characters.

我不确定如何实现这种排序,非常感谢您的帮助.

I'm not sure how to achieve this sorting and would really appreciate some help.

推荐答案

假定将值逐行存储在列表中,如下所示:

Assume values stored row-by-row in list, like that:

a = [['D', 'C', 'B', 'A'],
     ['1', '3', '2', '0'],
     ['1', '3', '2', '0']]

要对该数组排序,可以使用以下代码:

To sort this array you can use following code:

zip(*sorted(zip(*a), key=lambda column: column[0]))

其中column [0]-要排序的值(您可以使用column 1 等)

where column[0] - value to be sorted by (you can use column1 etc.)

输出:

[('A', 'B', 'C', 'D'),
 ('0', '2', '3', '1'),
 ('0', '2', '3', '1')]

注意 : 如果您使用的是大型数组,并且执行时间确实很重要,请考虑使用numpy,它具有适当的方法:

Note: If you are working with pretty big arrays and execution time does matter, consider using numpy, it has appropriate method: NumPy sort

这篇关于如何排序2D清单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆