如何从列表中的列表中删除撇号

问题描述 投票:-2回答:1

我正在尝试从.csv文件计算行平均值,并返回每行的平均值列表。目前,我可以得到

in_ = [['1,2'], ['1,1,1,1'], ['-1,0,1'], ['42,17']]

但我需要删除撇号以平均个别列表!我尝试过使用int(),但没有运气。

我想要的输出

out = [[1, 2], [1, 1, 1, 1], [-1, 0, 1], [42, 17]]

我目前的代码是:

def line_averages(filename):
    """takes a file and returns the average values of each line in a
    .csv file"""
    f = open(filename, 'r')
    lines = f.readlines()
    #print(lines)
    f.close()
    words = []
    for line in lines:
        words.append(line.split())
    for i in words:
        words.replace("'", "")
    return words
python python-3.x csv
1个回答
3
投票

您在这里重新发明了CSV读取器轮。使用csv module来代替你处理分裂;然后我们只需要将字符串列转换为整数:

def line_averages(filename):
    """takes a file and returns the average values of each line in a
    .csv file"""
    with open(filename, 'r', newline='') as f:
        reader = csv.reader(f)
        for row in reader:
            yield [int(c) for c in row]

这会生成一个生成器,迭代会为你提供整数行:

for row in line_averages(some_file_name):
    # do something with each row

您还可以返回列表列表:

def line_averages(filename):
    """takes a file and returns the average values of each line in a
    .csv file"""
    with open(filename, 'r', newline='') as f:
        reader = csv.reader(f)
        return [[int(c) for c in row] for row in reader]

您的尝试在空格上分割,而不是在逗号上分割。您必须在','上明确拆分,并将列转换为整数:

def line_averages(filename):
    """takes a file and returns the average values of each line in a
    .csv file"""
    with open(filename, 'r') as f:
        return [[int(c) for c in line.split(',')] for line in f]

我在这里使用nested list comprehensions来生成列表列表,将每行从文件转换为整数列表。

我也把这个文件用作context manager in a with statement;这确保无论托管块中发生什么,文件都会关闭;无需手动关闭它。

我还使用该文件作为迭代器;每次迭代(就像for循环一样),你得到文件中的下一行。没有必要使用file.readlines()读取前面的所有行。

© www.soinside.com 2019 - 2024. All rights reserved.