我的代码在应该有值的时候返回一个满是零的列表

2024-09-26 22:44:58 发布

您现在位置:Python中文网/ 问答频道 /正文

如问题所述,我编写了一段代码,用于从一个大数据集中的多个行中查找一些数据的平均值。出于某种原因,代码现在只返回一个包含零的元组列表,以前在测试较小的数据位时,它会显示值,但在细化代码之后,它现在就不起作用了。我好像看不出我把什么东西弄坏了,谢谢你的帮助

我已经将整个函数粘贴到下面,我似乎看不到错误。我猜这和循环有关,但我不明白哪里有问题

def makeAverageList(input,col1=1,col2=2,monthavg=200):
    f = open(input + ".txt", "r")
    col1avg = []
    col2avg = []
    points = []
    length = len(f.readlines())
    count = 1
    maxcount = float(length/monthavg)
    while True:
        lines = list(islice(f, monthavg))
        col1list = []
        col2list = []
        linelist = []
        for i in lines:
            linelist.append(i[1:-2])
        for l in linelist:
            line = []
            line = l.split(",")
            col1list.append(float(line[col1]))
            col2list.append(float(line[col2]))
        A = float(sum(col1list))
        col1avg.append(float(A/monthavg))
        B = float(sum(col2list))
        col2avg.append(float(B/monthavg))
        count = count + 1
        if not count < maxcount:
            break
    for z in range(len(col1avg)):
        P = (float(col1avg[z]), float(col2avg[z]))
        points.append(P)
    return points

print(makeAverageList("data.monthly_nh_clean"))

[(0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0)]

数据集有许多行值,如下所示:

,1850.08,-0.844,-0.921,-0.747,-1.036,-0.652,-1.374,-0.314,-1.051,-0.635,-1.413,-0.274

,1850.17,-0.053,-0.119,0.032,-0.254,0.148,-0.621,0.515,-0.270,0.166,-0.661,0.556

,1850.25,-0.699,-0.794,-0.632,-0.891,-0.508,-1.124,-0.274,-0.910,-0.495,-1.174,-0.229

在代码中,我格式化它,拆分它,并从中获取值。我不明白为什么它停止工作了


Tags: 数据代码inforcountlinefloatpoints
1条回答
网友
1楼 · 发布于 2024-09-26 22:44:58

只能对打开的文件迭代一次。第一次,您消耗的所有输入是确定行数。第二次,您尝试读取while循环中的行,文件已经被使用,并且没有给出结果,因此是一个空列表linelist

要简化所有操作,您不需要maxcount,但需要检查空的col1list

def makeAverageList(input, col1=1, col2=2, monthavg=200):
    points = []
    with open(input + ".txt") as lines:
        while True:
            col1list = []
            col2list = []
            for line in islice(lines, monthavg):
                line = line.strip(',').split(",")
                col1list.append(float(line[col1]))
                col2list.append(float(line[col2]))
            if not col1list:
                # end of file
                break
            avg1 = sum(col1list) / len(col1list)
            avg2 = sum(col2list) / len(col2list)
            points.append((avg1, avg2))
    return points

相关问题 更多 >

    热门问题