-4

if I have a file (file.txt or file.dat) with two columns (let say x and y):

   x      y  
1467153  12309  
1466231  21300  
  .        .  
  .        .  
1478821  10230 

I want to sort each (x,y) with x as key value in ascending order. How to do this exactly in python?

ZdaR
  • 22,343
  • 7
  • 66
  • 87
ejy yoni
  • 1
  • 4

1 Answers1

3

Python has the built-in function sorted which you can use to sort a list.

data = """1467153  12309  
1466231  21300  
1478821  10230
"""
l = sorted([list(map(int, line.split())) # convert each pair to integers
            for line                     # iterate over lines in input
            in data.split("\n")          # split on linebreaks
            if line],                    # ignore empty lines
    key=lambda x: x[0])                  # sort by firt element of pair
print(l)

Output:

[[1466231, 21300], [1467153, 12309], [1478821, 10230]]

Edit: If your input is two lists of integers, do this:

xs = [1467153, 1466231, 1478821]
ys = [12309, 21300, 10230]
l = sorted(zip(xs, ys), key=lambda x: x[0])
print(l)

Output:

[(1466231, 21300), (1467153, 12309), (1478821, 10230)]