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. But don't know how to use it. The lambda function is clearly explained here, but the challenges are
1) Parameter list should be something like for row in lines
2) The code block should be something like row[0]
But this syntax is incorrect and I know that!
sorted( lines, key=lambda for row in lines : row[0])
答案 0 :(得分:3)
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 :
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]