0

So i have a text file containing names,scores and class in there e.g.

= ('test', ' in class', '1', ' has got a score of', 1)

How can i sort it (text file) so that it sorts it numerically by the score?

kenorb
  • 155,785
  • 88
  • 678
  • 743
Lars
  • 3
  • 1
  • 2
  • 2
    What have you tried so far? You should have an attempt at code when you post here. – SuperBiasedMan May 19 '15 at 10:55
  • I have tried all the codes on here=http://stackoverflow.com/questions/3121979/how-to-sort-list-tuple-of-lists-tuples?rq=1 – Lars May 19 '15 at 10:56
  • 1
    possible duplicate of [Sorting names by their high scores](http://stackoverflow.com/questions/17632428/sorting-names-by-their-high-scores) – Eric Levieil May 19 '15 at 11:04
  • No i just tired that and it did not work. it said=ValueError: too many values to unpack – Lars May 19 '15 at 11:11

2 Answers2

2

First, read the file into a list of lists:

with open(filepath, 'r') as file:
    list = []
    for line in file:
        list.append(line[1:-1].split(","))

Now you have something like this:

list == [['test', ' in class', '1', ' has got a score of', 3],
         ['test', ' in class', '1', ' has got a score of', 5],
         ['test', ' in class', '1', ' has got a score of', 1],
         ['test', ' in class', '1', ' has got a score of', 2]]

Then sort lists inside the list:

list.sort(key=lambda x: int(x[4]))

This results in this sorted list:

list = [['test', ' in class', '1', ' has got a score of', 1],
        ['test', ' in class', '1', ' has got a score of', 2],
        ['test', ' in class', '1', ' has got a score of', 3],
        ['test', ' in class', '1', ' has got a score of', 5]]
SuperBiasedMan
  • 9,814
  • 10
  • 45
  • 73
konart
  • 1,714
  • 1
  • 12
  • 19
2

You can use the sorted() function as

sorted_lines = sorted(lines, key = lambda x : x[4] )

Example

>>> lines = [ ('test', ' in class', '1', ' has got a score of', 1),
            ('test', ' in class', '4', ' has got a score of', 4),
            ('test', ' in class', '5', ' has got a score of', 5),
            ('test', ' in class', '3', ' has got a score of', 3),
            ('test', ' in class', '2', ' has got a score of', 2) ]

>>> sorted_lines = sorted(lines, key = lambda x : x[4] )
>>> soted_lines
('test', ' in class', '1', ' has got a score of', 1)
('test', ' in class', '2', ' has got a score of', 2)
('test', ' in class', '3', ' has got a score of', 3)
('test', ' in class', '4', ' has got a score of', 4)
('test', ' in class', '5', ' has got a score of', 5)
nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52
  • Looks like you were 3 minutes later, with just about the same answer. There's a good explanation of `lambda` [here](https://stackoverflow.com/a/17632482/6505499). – bballdave025 Jul 06 '18 at 20:48