如何从列表

时间:2017-12-22 14:53:44

标签: python python-3.x csv

我尝试从.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

1 个答案:

答案 0 :(得分: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()预先读取所有行。