-2

I've got a file where each line is in the following format: string, number

For example:

whats up, 843

peace out, 23

hello, 91

hi, 11

see ya later, 5

I would like to order the file in ascending order, by the number value on the right side of the comma.

For example:

see ya later, 5

hi, 11

peace out, 23

hello, 91

whats up, 843

I know in python you can use the sorted() method to sort a list of numbers in ascending order, but I'm not exactly sure how I would extract the number on the right side of the comma and sort the file.

jokexel
  • 19
  • 4

3 Answers3

0

You can use sorted() :

>>> s="""whats up, 843
... 
... peace out, 23
... 
... hello, 91
... 
... hi, 11
... 
... see ya later, 5"""

>>> l=[i for i in s.split('\n') if i]
>>> l
['whats up, 843', 'peace out, 23', 'hello, 91', 'hi, 11', 'see ya later, 5']
>>> print '\n'.join(sorted(l,key=lambda x : int(x.split()[-1])))
see ya later, 5
hi, 11
peace out, 23
hello, 91
whats up, 843
Mazdak
  • 105,000
  • 18
  • 159
  • 188
0

What you have is a list of tuples. You can use a similar solution to this question for the final sorting. However, you first need to get your data file into this list of tuples.

data = []
for line in open('test.txt'):
    data.append((line.split(",")[0].strip(),int(line.split(",")[1].strip())))

data.sort(key=lambda x: x[1])

print data

What this does is read in each line, and split it on the comma (,). Extra spaces around the first element are stripped and the second element is converted to an integer. Then, we sort the list.

This outputs the following list:

[
    ('see ya later', 5), 
    ('hi', 11), 
    ('peace out', 23), 
    ('hello', 91), 
    ('whats up', 843)
]
Community
  • 1
  • 1
Andy
  • 49,085
  • 60
  • 166
  • 233
0

To use sorted it is sorted(dict1, key=dict1.get)

If you print that, as I did below, it should work perfectly.

def test():
    testList = {"whats up": 843, "peace out": 23, "hello": 91, "hi": 11, "see ya later": 5}
    print(sorted(testList, key=testList.get))
jack3604
  • 93
  • 1
  • 1
  • 4