简体   繁体   English

根据第一列对2d数组进行排序

[英]Sorting a 2d array based on the first column

I have a data file with some integer numbers 我有一个带有一些整数的数据文件

2 8 
6 7 3
4
1 3 4 2

I want to read lines and sort them based on the first element in each row. 我想读取行并根据每行中的第一个元素对它们进行排序。 So the output should be 所以输出应该是

1 3 4 2
2 8
4
6 7 3

The following statements read the file and store each line in an array 以下语句读取文件并将每行存储在数组中

fs = open('test.txt')
lines = [line for line in fs if line.strip()]

Now I want to use sorted with the proper key. 现在我想使用正确的键sorted But don't know how to use it. 但不知道如何使用它。 The lambda function is clearly explained here , but the challenges are 这里清楚地解释 lambda函数,但挑战是

1) Parameter list should be something like for row in lines 1)参数列表应该类似for row in lines

2) The code block should be something like row[0] 2)代码块应该像row[0]

But this syntax is incorrect and I know that! 但是这种语法不正确,我知道!

sorted( lines, key=lambda for row in lines : row[0])

You need to split your lines then use sorted and not that its better to sort your lines based on the integer values of the numbers, because for the digits with length more that tow it will compare incorrectly (because of lexicographically sorting ): 您需要拆分行然后使用已排序而不是更好地根据数字的整数值对行进行排序,因为对于长度更多的数字,它将被错误地比较(因为按字典顺序排序):

lines = sorted([line.split() for line in fs if line.strip()],key=lambda x :int(x[0]))

Or use operator.itemgetter as the key which performs better in this case : 或者使用operator.itemgetter作为在这种情况下表现更好的键:

from operatior import itemgetter
lines = sorted([line.split() for line in fs if line.strip()],key=int(itemgetter(0)))

And the you can join the lines : 你可以参加这些台词:

new_lines = [' '.join(i) for i in lines] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM