-4

I have a python program for sorting out class scores. My Class1 text file looks like this:

Elizabeth, 2, 7, 3

Anna, 9, 6, 4

Jenny, 8, 1, 5

Victoria, 1, 4, 7

This is my code so far:

file=open("Class1.txt","r")

studentscores= []

for row in file:

    studentscores.append(row.strip())

studentscores2=[]

for item in studentscores:

    studentscores2.append(item.split(","))

I'm struggling how to how to convert the string into integers so that I can sort the numbers? I would appreciate some help.

ZdaR
  • 22,343
  • 7
  • 66
  • 87
  • 2
    ...with [`int`](https://docs.python.org/2/library/functions.html#int)? – jonrsharpe Apr 29 '15 at 19:36
  • 2
    possible duplicate of [Parse String to Float or Int](http://stackoverflow.com/questions/379906/parse-string-to-float-or-int) – Rod Apr 29 '15 at 19:37

3 Answers3

2
s = '''Elizabeth, 2, 7, 3
   ...: Anna, 9, 6, 4
   ...: Jenny, 8, 1, 5
   ...: Victoria, 1, 4, 7'''
[int(word) for line in s.splitlines() for word in line.split(',') if word.strip().isdigit()]
[2, 7, 3, 9, 6, 4, 8, 1, 5, 1, 4, 7]
Adem Öztaş
  • 20,457
  • 4
  • 34
  • 42
  • I dislike this approach, since it can't handle any score over one digit long. I would split by commas instead, treat the first element as a name, and the rest as scores. – Shashank Apr 29 '15 at 19:54
  • Actually I just realized my comment made no sense, since split produces a list. A better way would be: `[[int(word) for word in (word.strip() for word in line.split(',')) if word.isdigit()] for line in s.splitlines()]` This produces a list of lists of the form: `[[2, 7, 3], [9, 6, 4], [8, 1, 5], [1, 4, 7]]` But your approach is fine as well :) Upvoting. – Shashank Apr 29 '15 at 20:14
  • Or, more simply: `[[int(word) for word in line.split(',') if word.strip().isdigit()] for line in s.splitlines()]` This allows each student's scores to be handled separately in its own list. – Shashank Apr 29 '15 at 20:18
0

your code can be effectively rewritten as :

scorecard = []
with open("Class1.txt","r") as marks_file:
    for scores in marks_file.readlines():
        scorecard.append(map(int, scores.split(", ")[1:]))

The map function here is used to implement a function over a given list, and for converting a valid string to an integer we use int("100") where "100" is a string which is converted to an integer, So we use the map function to do the same over the given set of strings.

ZdaR
  • 22,343
  • 7
  • 66
  • 87
-1

Look into the map() built in function in python

Assuming studentscores is the name of the list, just do

map(int,studentscores)

letsc
  • 2,515
  • 5
  • 35
  • 54