列表中的值发生了什么变化?

2024-04-26 14:25:06 发布

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

为了自我练习,我正在编写一个字典程序,它将数据存储在以下数据结构中:[(average,month),(average,month),....,(average,month)]。数据文件被称为表格.csv可在以下链接中找到:

http://www.cse.msu.edu/~cse231/PracticeOfComputingUsingPython/05_ListsTuples/AppleStock/

我的问题是,当这个条件变为false时,为什么列表testList[x][0]会变成空白?地址:

if dates == UniqueDates[x]:

x = 0,这样testList[0][0],条件是True,列表是[474.98, 468.22, 454.7, 455.19, 439.76, 450.99]。但是,当它变成False时,同样的列表testList[0][0],神秘地变成了[ ]。为什么不保留列表中的值?你知道吗

f = open('table.csv','r').readlines()
col = 6

testList = []
uniqueDates = []

x = 0
for i in range(1,len(f)):
    dates = f[i].split(',')[0][:7]
    column = float(f[i].split(',')[col])
    if dates not in uniqueDates:
        uniqueDates.append(dates)
        testList.append(())
        testList[x] = [],dates
    if dates == uniqueDates[x]:
        testList[x][0].append(column)
    else:
        testList[x][0].append((mean(testList[x][0]),uniqueDates[x]))
        x += 1
        testList[x][0].append(column)

Tags: csvin列表if字典columncol条件
1条回答
网友
1楼 · 发布于 2024-04-26 14:25:06

考虑这一部分:

if dates not in uniqueDates:
    uniqueDates.append(dates)
    testList.append(())
    testList[x] = [],dates

第一次执行此操作是在处理第7行时,即月份第一次更改。在执行这个部分之前,x == 0;所以这个块中的最后一行替换了testList的第一个元素。我想您希望它替换刚才附加的新空元素。你知道吗

我想你想要的是把最后两行简单地组合成一行:

if dates not in uniqueDates:
    uniqueDates.append(dates)
    testList.append(([],dates))

相关问题 更多 >