1

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])
Community
  • 1
  • 1
mahmood
  • 23,197
  • 49
  • 147
  • 242

1 Answers1

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] 
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • How python identify that `x` is `line.split()`? – mahmood Jul 31 '15 at 20:10
  • `x` is the parameter defined by the anonymous `lambda`. `myfunc = lambda x:` is roughly equivalent to `def myfunc(x):`. – TigerhawkT3 Jul 31 '15 at 20:16
  • 1
    @mahmood since `lambda` is a function that takes the argument `x` python passes the iterable argument in `sorted` function to the key function. – Mazdak Jul 31 '15 at 20:16
  • Regarding the "incorrect lexicographically sorting", do you mean that the first statement is error prone? Do you mean that the second method is preferred? Also is the third statement for joining mandatory? – mahmood Jul 31 '15 at 20:18
  • @mahmood The first method has nothing to do with *lexicographically sorting* and yes the second method is preferred because of its performance. – Mazdak Jul 31 '15 at 20:23
  • @mahmood Also `join` is the proper way for joining an iterable of strings in python and a list comprehension is a good and fast way. any way you can try some other ways like use `+` to joining the string :) or .. – Mazdak Jul 31 '15 at 20:25