18044

Sorting information from a file in python

Question:

I have a .txt file that has the following information in it that displays a users name and then 3 scores that they have scored in a quiz:

callum,10,7,9 carl,10,10,10 hollie,1,4,7 brad,4,8,3 kyle,7,2,0

I would like to sort it into alphabetical order displaying the users highest score after their name.

Answer1:

<ol><li>Read file content.</li> <li>Use readlines() method to read lines from file.</li> <li>Use split() to get Name and score.</li> <li>Add in dictionary: Name is Key and Value is total score.</li> <li>Get all keys from the result dictionary.</li> <li>User sort() method to sort list by alphabets.</li> <li>Print result by alphabets order.</li> </ol>

Code

p = "/home/vivek/Desktop/test_input.txt" result = {} with open(p, "rb") as fp: for i in fp.readlines(): tmp = i.split(",") try: result[(tmp[0])] = eval(tmp[1]) + eval(tmp[2]) + eval(tmp[3]) except: pass alphabetical_name = result.keys() alphabetical_name.sort() for i in alphabetical_name: print "Name:%s, Highest score: %d"%(i, result[i])

Output:

$ python test.py Name:brad, Highest score: 15 Name:callum, Highest score: 26 Name:carl, Highest score: 30 Name:hollie, Highest score: 12 Name:kyle, Highest score: 9

Answer2:

So i would first of all isolate all the lines:

with open('filename') as f: lines = f.readlines()

So i will continue assuming I have a list called lines with the following content:

lines = ["callum,10,7,9","carl,10,10,10","hollie,1,4,7","brad,4,8,3","kyle,7,2,0"]

Then I will firstly sort the line by name

lines = sorted(lines)

Then for each line you want to isolate the marks, sort them and print them back:

for line in lines: #name is what there is before the first comma name = line[:line.find(",")] #marks are what there is after the second comma and are comma separated marks = line[line.find(",")+1:].split(",") #sort the marks marks = sorted(marks,key=int) #if you want to print only the highest print "%s,%s"%(name,marks[-1])

Recommend

  • Convert different encodings to ascii
  • How to sort results based on join table in Rails?
  • SQL: Find top-rated article in each category
  • Extracting words from txt file using python
  • How to find the largest array from a multi dimensional array [duplicate]
  • C++/VS2005: Defining the same class name in two different .cpp files
  • How to make a variable by extracting specific line?
  • How do i do the following curl command in Java
  • Convert data type in R or Python
  • Failed to read schema document 'http://www.springframework.org/schema/tool/spring-tool-4.1.xsd&
  • Python: Split a String Field into 3 Separate Fields using Lambda
  • how can I compare dates in array to find the earliest one?
  • Divide a $1 by 3 and adjusting 1 cent
  • How do I shift the decimal place in Python?
  • R - Combining Columns to String Based on Logical Match
  • ilmerge with a PFX file
  • Cannot connect to cassandra from Spark
  • Nant, Vault & Windows Integrated Authentication
  • Read text file and split every line in MSBuild
  • Problems to linebreak with an int in JLabel
  • Align navbar back button on right side
  • DotNetZip - Calculate final zip size before calling Save(stream)
  • Javascript Callbacks with Object constructor
  • Trying to switch camera back to front but getting exception
  • ORA-29908: missing primary invocation for ancillary operator
  • Warning: Can't call setState (or forceUpdate) on an unmounted component
  • Return words with double consecutive letters
  • php design question - will a Helper help here?
  • how to add data labels for bar graph in matlab
  • InvalidAuthenticityToken between subdomains when logging in with Rails app
  • SQL merge duplicate rows and join values that are different
  • AngularJs get employee from factory
  • Load html files in TinyMce
  • Free memory of cv::Mat loaded using FileStorage API
  • Angular 2 constructor injection vs direct access
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • LevelDB C iterator
  • Authorize attributes not working in MVC 4
  • Can't mass-assign protected attributes when import data from csv file
  • Programmatically clearing map cache