How do I sort data highest to lowest in Python from a text file?

2024/11/16 8:33:06

I have tried multiple methods in doing this but none of them seem to work The answer comes up alphabetically instead

f=open("class2.txt", "r")
scores=myfile.readlines()
print(sorted(scores))
f.close()['Anne,   3\n', 'Dave,   10', 'Jack,   4\n', 'Lucy,   8\n']

Also is there any way to get rid of the "/n" when it goes to the shell?

Answer

Based on the inputs and outputs, I'm guessing you're trying to sort the input names by the associated values. To sort numerically, you can either parse all the values pairs, or use a key function with sorted that does it for you (without storing the result anywhere). For example:

# This could be a lambda function, but I'm splitting it out for clarity
def getlinevalue(line):intpart = line.split()[-1]  # Get the last whitespace separated group (assumed to be legal integer)return int(intpart)  # Convert to int, which will sort numericallywith open("classt2.txt") as f:stripnewlines = (line.rstrip() for line in f)# reverse=True needed to sort highest to lowest; natural sort for int is lowest to highestprint(sorted(stripnewlines, reverse=True, key=getlinevalue))# If the goal is to print one pair per line, replace the print above with:for x in sorted(stripnewlines, reverse=True, key=getlinevalue):print(x)# Or as a one liner (require Py3, or from __future__ import print_function on Py2):print(*sorted(stripnewlines, reverse=True, key=getlinevalue), sep="\n")

The output from print(sorted(stripnewlines, reverse=True, key=getlinevalue)) would be (modulo some whitespace; the screenshot makes it hard to tell how much whitespace is after the comma, so I'm just using a single space):

['Dave, 10', 'Lucy, 8', 'Jack, 4', 'Anne, 3']

which is what you seem to want.

Explanation of code as requested in the comments:

  1. In getlinevalue, we're splitting the provided string on whitespace (str.split does this when not given an argument), then taking the last value from the split with [-1] (indexing with negative numbers starts from the end). So something like 'Dave, 10' is stored to intpart as '10'. Then we convert the string '10' to its integer value with int() and return it
  2. with open("classt2.txt") as f: opens the file for read and assigns the result to f; when the indented with block finishes, the file is closed for you (even if the block exits due to exceptions or returning from a function)
  3. stripnewlines = (line.rstrip() for line in f) Creates a generator expression (sort of like a lazily evaluated list comprehension that can only be iterated once) that reads a line at a time and uses str.rstrip() to remove all trailing whitespace (e.g. the new line; you could use str.rstrip("\r\n") to only remove the newline, not trailing tabs or spaces, but the key function would need to be tweaked). We could use a list comprehension instead of a generator expression, but since sorted will create the list for us anyway, we're being lazy to avoid having both the sorted and unsorted list stored at the same time (alternatively, a list comprehension could be followed by a .sort(...) call on the result, which would also avoid keeping two lists in memory, but .sort(...) doesn't return anything, so we'd have more lines of code).
  4. sorted(stripnewlines, reverse=True, key=getlinevalue) is just like the sorted you used in your attempt except it sorts each (rstrip-ed) line based on the result of calling getlinevalue on it (it only calls the key function once per value, which is why key is superior to cmp; cmp would have to convert each value log(n) times during the sort, on average, or n log(n) conversions total; key converts each value once, and performs a total of n conversions). So it sorts 'Dave, 10' relative to 'Anne, 3' by comparing the result of calling getlinevalue('Dave, 10') (10) to getlinevalue('Anne, 3') (3). Since numbers sort in ascending order (lowest to highest) normally (so 3 would sort before 10) and you want descending order (highest to lowest) we also pass reverse=True to reverse the "natural" sort of the integers.
  5. The final one-liner uses the "splat" operator (*) to convert the list resulting from the sorted call to sequential positional arguments to print; for Python 3's print function (or the print function you get in Python 2 with from __future__ import print_function that replaces the normal print statement of Py2), each argument is printed, with sep printed between each argument (defaults to a single space, ' '), and when all arguments are printed, follows it up with the value of end (defaults to a new line, "\n"). So that would let you print the input lines from highest to lowest on separate output lines rather than printing the representation of the sorted list on a single line.
https://en.xdnf.cn/q/119211.html

Related Q&A

Determine if a variable is an instance of any class

How to determine if a variable is an instance in Python 3? I consider something to be an instance if it has __dict__ attribute.Example:is_instance_of_any_class(5) # should return False is_instance_of…

Method POST not allowed with Django Rest Framework

Im trying to create a JSON API compliant rest service using Django Rest Framework JSON API: https://django-rest-framework-json-api.readthedocs.io/en/stable/index.htmlI think Im stuck at the Django Rest…

Running multiple queries in mongo`

I have a collection and want to get a set of results that met a set of conditions. I understand the Mongo doesnt let you use joins so I would need to run separate queries and join the results into a si…

Error in Calculating neural network Test Accuracy

I tried to train my neural network, and then evaluate its testing accuracy. I am using the code at the bottom of this post to train. The fact is that for other neural networks, I can evaluate the testi…

Adding stats code to a function in Python

Im relatively new to Python and trying to learn how to write functions. The answer to this post highlights how to get certain stats from a dataframe and I would like to use it in a function.This is my…

Multiple Histograms, each for a label of x-axis, on the same graph matplotlib

I am trying to plot a graph to show different behaviors by males and females with regards to a certain activity, for different age-groups. So, if the age groups are: [1-10,11-20,21-30...] I would like …

How can I split a string in Python? [duplicate]

This question already has answers here:Closed 11 years ago.Possible Duplicates:Split python string every nth character?What is the most “pythonic” way to iterate over a list in chu…

How to enable media device access in Edge browser using Selenium?

I have a Selenium test I want to run in Edge against a page which uses the webcam and microphone. In order for those media devices to work in the browser, the user has to allow the site access to the d…

Print specific rows that are common between two dataframes

i have a dataframe (df1) like this id link 1 google.com 2 yahoo.com 3 gmail.comi have another dataframe(df2) like this: id link numberOfemployees 1 linkedin.com …

What is the problem with buttons connection in PyQt5?

I have the problem that I cannot connect the implementation between two buttons. After I pressed the "Grayscale" button and got the grayscale image, I pressed the "Canny" button but…