1

I got this, but how do I go from this:

['99', '88', '77', '66\n', '11', '22', '33', '44\n', '78', '58', '68', '88\n']

to:

[[99, 88, 77, 66], [11, 22, 33, 44], [78, 58, 68, 88]]

This is the function i used to get the first output:

def class_avg(open_file):
    new = []
    number = []

    for i in open_file:
        student = i.split(',')
        for grade in student[4:]:
            new.append(grade)
    return new

This is the file format:

Smith, Joe,9911991199,smithjoe9,99,88,77,66
Ash, Wood,9912334456,ashwood,11,22,33,44
Full, Kare,9913243567,fullkare,78,58,68,88
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 6
    How did you get that first line, I bet we can fix your original file read so you don't have this issue in the first place – Cory Kramer Nov 03 '17 at 16:56
  • 4
    I am smelling an [XY](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) problem here. Maybe you might want to show us your code. – Ozgur Vatansever Nov 03 '17 at 16:57
  • yes, it's much easier to fix the output. create a new list in the loop, and strip the line, convert to integer, you're done – Jean-François Fabre Nov 03 '17 at 17:01
  • `student = i.strip().split(',')` would give you the items with the trailing new line character cleared. – Ozgur Vatansever Nov 03 '17 at 17:02
  • https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunk, apply this, then you can iterate over it using `str.strip` for removing newlines and `map` for applying ints, or just do `int(s.strip())` – uspectaculum Nov 03 '17 at 17:05

6 Answers6

5

Here's how you should be reading processing your file to avoid the problem in the first place:

def class_avg(open_file):
    new = []    
    for line in open_file:
        student = line.strip().split(',')
        new.append(list(map(int, student[4:])))
    return new

As @Jean-FrançoisFabre notes, .strip isn't really necessary if you're going to convert to int since it deals with whitespace. You could really just do something like:

return [[int(s) for s in line.split()[4:]] for line in open_file]

Or better yet, use the csv module:

import csv
with open('path_to_my_file.txt') as f:
    reader = csv.reader(f)
    data = [[int(x) for x in row[4:]] for row in reader]
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
1

Try something like this

output = []
sub_l = []
for i in your_input:
    if "\n" in i:
        sub_l.append(int(i.replace("\n","")))
        output.append(sub_l)
        sub_l=[]
    else:
        sub_l.append(int(i))

print(output)
NS0
  • 6,016
  • 1
  • 15
  • 14
  • This is nearly identical to the answer posted by Van Peer. Additionally, `int()` will strip whitespace, so the `replace()` is unnecessary. – TemporalWolf Nov 03 '17 at 17:21
0

If you like iteration tricks...

>>> l = ['99', '88', '77', '66\n', '11', '22', '33', '44\n', '78', '58', '68', '88\n']
>>> [[int(x) for x in sub] for sub in zip(*[iter(l)]*4)]
[[99, 88, 77, 66], [11, 22, 33, 44], [78, 58, 68, 88]]
timgeb
  • 76,762
  • 20
  • 123
  • 145
0
l=['99', '88', '77', '66\n', '11', '22', '33', '44\n', '78', '58', '68', '88\n']

y=[]
z=[]

for x in l:
    y.append(int(x))
    if '\n' in x:
        z.append(y)
        y=[]

print (z)

Output

[[99, 88, 77, 66], [11, 22, 33, 44], [78, 58, 68, 88]]
Van Peer
  • 2,127
  • 2
  • 25
  • 35
0

Try this function: You can change stepper if you want to change the length, of the sub list.

def list_divider(ls,stepper=4):
    #Get rid of the \n.
    ls=list(map(str.strip,ls))
    result=[]
    pos = 0
    #Slice the list  by moving pos 4 steps each time
    while pos<=len(ls)-1:
        result.append(ls[pos:pos+stepper])
        pos+=stepper
    return result

I hope that was helpful

Aghiad Alzein
  • 159
  • 1
  • 6
0

Here's a fairly concise way to do it that uses the csv module to read the file and the itertools module to reformat the data for processing calcultions.

import csv
import itertools

def class_avg(open_file):
    grades = tuple(itertools.chain.from_iterable(  # Put all grades into single sequence.
                    itertools.chain(map(int, row[4:])  # Convert grades in row to integers.
                        for row in csv.reader(open_file))))
    total = sum(grades)
    return total / len(grades)

with open('class_grades.txt', newline='') as file:
    print(class_avg(file))  # -> 61.0

The value printed is for the values in the sample file in your question.

martineau
  • 119,623
  • 25
  • 170
  • 301