James Walker
James Walker

Reputation: 35

List of strings into sublist of strings

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

Upvotes: 1

Views: 131

Answers (6)

martineau
martineau

Reputation: 123531

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.

Upvotes: 0

Van Peer
Van Peer

Reputation: 2167

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]]

Upvotes: 0

Aghiad Alzein
Aghiad Alzein

Reputation: 179

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

Upvotes: 0

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96350

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]

Upvotes: 5

timgeb
timgeb

Reputation: 78790

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]]

Upvotes: 0

NS0
NS0

Reputation: 6126

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)

Upvotes: 1

Related Questions