【问题标题】:Python Numerical Error Arising in Series of Nested Lists一系列嵌套列表中出现的 Python 数值错误
【发布时间】:2015-12-08 18:56:56
【问题描述】:

我正在尝试编写一个脚本来解析一个包含位置和时间信息的非常大的数据文件,并将该信息存储在一个数组(即列表列表)中,但是,由于某种原因,我的代码正在编写多个子列表中的相同数字。

# Import data from inputFile into list
with open(r"C:\..file.dat") as inputFile:
    inputList = list(inputFile)

totalSegs = 775
totalPrds = 938

stressPrd = 1
segNum = 1
testList = []
masterList = []

while stressPrd <= totalPrds: #build a list of times
    testList.append(0)
    stressPrd += 1

while segNum <= totalSegs: #build a list of locations
    masterList.append(testList) #list of time periods by location
    segNum += 1

stressPrd = 1
segNum = 1

for inputItem in inputList: #read data from file and write to lists
    if inputItem != '\n'
        inputItem = inputItem.split()
        if int(inputItem[3]) == int(segNum):
            testVar = float(masterList[segNum - 1][stressPrd - 1])
            testVar += float(inputItem[6])
            masterList[segNum - 1][stressPrd - 1] = testVar
        else:
            segNum += 1
            if segNum <= totalSegs:
                testVar = float(masterList[segNum - 1][stressPrd - 1])
                testVar += float(inputItem[6])
                masterList[segNum - 1][stressPrd - 1] = testVar
            else:
                segNum = 1
                stressPrd += 1
                testVar = float(masterList[segNum - 1][stressPrd - 1])
                testVar += float(inputItem[6])
                masterList[segNum - 1][stressPrd - 1] = testVar

应该发生的是,来自同一时间 (stressPrd) 的同一位置 (segNum) 的数据被求和并存储在由 stressPrd 组织的子列表中,然后跨时间给定位置的该列表由 segNum 存储在父列表。然而,实际发生的情况是脚本将给定时间 (stressPrd) 内所有位置的所有数据相加,并且该总和存储在每个位置子列表中。

我尝试插入一些打印语句来同时跟踪多个子列表的情况,并且它们都开始同时计算相同的总和。我的变量 segNum 和 stressPrd 似乎都正确递增,并且我可以告诉我的 If 语句正在正确执行,所以我无法找出问题的根源。

作为我想要的结果的一个非常简化的示例:

Data:
Loc    Time1    Time2
A      6        1
A      2        2
B      2        3
C      5        4
C      1        1

Result:
[[8,3],[2,3],[6,5]]

提前致谢!

【问题讨论】:

    标签: python list nested-lists


    【解决方案1】:

    如果您正在处理表格数据,我强烈建议您切换到 pandas,而不是尝试调试此处发生的特定问题。这是一个非常简单的问题:

    In [16]: import pandas as pd
    
    In [17]: from StringIO import StringIO
    
    In [18]: datatable = """Loc    Time1    Time2
    A      6        1
    A      2        2
    B      2        3
    C      5        4
    C      1        1"""
    
    In [19]: df = pd.read_csv(StringIO(datatable), sep=" +", engine="python")
    
    In [20]: df.groupby("Loc").sum()
    Out[20]:
         Time1  Time2
    Loc
    A        8      3
    B        2      3
    C        6      5
    

    如果您想要指定的特定格式,最后也很容易将其拉出:

    In [28]: [list(v[1].values) for v in df.groupby("Loc").sum().iterrows()]
    Out[28]: [[8, 3], [2, 3], [6, 5]]
    

    【讨论】:

      猜你喜欢
      • 2022-10-17
      • 1970-01-01
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-03
      • 2015-04-26
      相关资源
      最近更新 更多