简体   繁体   中英

Highest to Lowest from a textfile?

I'm pretty new to python and I have been having trouble in trying to print out a score list in the form of highest to lowest. The scorelist is saved in a text file and is set out like this...

Jax:6
Adam:10 
Rav:2 

I have looked in books but I haven't been getting anywhere, does anyone know how I could go about receiving the scores in the form of highest to lowest from a textfile. Thank You.

I am using Python 3.3.2 version.

try like this:

with open("your_file") as f:
    my_dict = {}
    for x in f:
        x = x.strip().split(":")
        my_dict[x[0]] = x[1]

    print sorted(my_dict.items(), key= lambda x:x[1], reverse=True)

First, you need to load the file (let say it's name is file.txt), then you need to read the values, sort it after that and then print it. It's not as difficult as it seems to be.

Works only when the scores are unique

# init a dictionary where you store the results
results = {}
# open the file with results in a "read" mode
with open("file.txt", "r") as fileinput:
    # for each line in file with results, do following
    for line in fileinput:
        # remove whitespaces at the end of the line and split the line by ":"
        items = line.strip().split(":")
        # store the result, the score will be the key
        results[int(items[1])] = items[0]
# sort the scores (keys of results dictionery) in descending order
sorted_results = sorted(results.keys(), reverse=True)

# for each score in sorted_results do the following
for i in sorted_results:
    # print the result in the format of the scores in your file 
    print "{}:{}".format(results[i],i)

The steps are explained in the example code.

The links to the relevant documentation or examples follows:

EDIT:

This version works even when there are more scores of the same value. (Thanks to @otorrillas for pointing out the problem)

# init a list where you store the results
results = []
# open the file with results in a "read" mode
with open("file.txt", "r") as fileinput:
    # for each line in file with results, do following
    for line in fileinput:
        # remove whitespaces at the end of the line and split the line by ":"
        items = line.strip().split(":")
        # store the result as a list of tuples
        results.append(tuple(items))

# first it sorts all the tuples in `results` tuple by the second item (score)
# for each result record in sorted results list do the following
for result_item in sorted(results, key=lambda x: x[1], reverse=True):
    # print the result in the format of the scores in your file 
    print "{}:{}".format(result_item[0], result_item[1])

Comments in the code describes the code. The main difference is that the code does not use dict any more and uses tuple instead. And it also uses sorting by a key.

Just for fun: if all you need to do is sort the data from a file you can use the UNIX sort command

sort -k 2 -t : -n -r $your_file

(the arguments are: sort by second key, split fields by ':', numeric sort, reverse order).

tldr

sorted([l.rstrip().split(':') for l in open('d.d')], key=lambda i:int(i[1]))

You need to operate on the lines in the file, that you can get simply as

[l for l in open('FILE')]

but possibly without the new lines

[l.rstrip() for l in open('FILE')]

and eventually split over the : colon character

[l.rstrip().split(':') for l in open('FILE')]

so that you have obtainined a list of lists

>>> print [l.rstrip().split(':') for l in open('FILE')]
[['Jax', '6'], ['Adam', '10'], ['Rav', '2']]

that is the thing that you want to have sorted. In species you want to sort it according to the numerical value of the 2nd field

>>> print [int(r[1]) for r in [l.rstrip().split(':') for l in open('FILE')]]
[6, 10, 2]

The sorted builtin accepts the optional argument key , a function to extract the part to compare in each element of the iterable to be sorted

>>> sd = sorted([l.rstrip().split(':')for l in open('FILE')],key=lambda r:int(r[1]))
>>> print sd
[['Rav', '2'], ['Jax', '6'], ['Adam', '10']]

and that's all folks...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM