简体   繁体   中英

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

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]

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)

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM