简体   繁体   English

字符串列表转换为字符串子列表

[英]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. 正如@Jean-FrançoisFabre指出的那样,如果您要转换为int .strip ,则.strip并不是真正必需的,因为它处理空格。 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: 或更妙的是,使用csv模块:

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. 这是一种相当简洁的方法,它使用csv模块读取文件,并使用itertools模块重新格式化数据以处理煅烧。

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. 打印的值是针对您问题中样本文件中的值的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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