数组数据在函数之外的变化

时间:2014-06-25 21:41:51

标签: python arrays

我正在编写一个功能来购买年度软件许可证&返还每月花费的金额。所以投入。

#[company id, user id, purchase amount, date in yy-mm format, day when customer first registered]
['55463', '114769', $200, '14-5', '2/14/2013']

会返回

['55463', '114769', $17.5, '14-5', '2/14/2013']
['55463', '114769', $17.5, '14-6', '2/14/2013']
['55463', '114769', $17.5, '14-7', '2/14/2013']
['55463', '114769', $17.5, '14-8', '2/14/2013']

等。我有一个功能可以根据需要打印出来。但是,当我尝试访问函数外部的数据时,我写入的数组突然只在上个月重复显示了多次。所以最后一个例子就是。

['55463', '114769', $17.5, '14-8', '2/14/2013']
['55463', '114769', $17.5, '14-8', '2/14/2013']
['55463', '114769', $17.5, '14-8', '2/14/2013']
['55463', '114769', $17.5, '14-8', '2/14/2013']

我无法解决这个问题,因为我和他的生活一样。非常感谢任何帮助。这是我的代码。我认为错误是在for循环中的某个地方开始,范围(11)中的x开始。谢谢你的帮助!

line_items = []
annualized = []
def csv_dict_reader(file_obj):
global board_info 
reader = csv.DictReader(file_obj, delimiter=',')
for line in reader:
    item = []
    item.append(line["company id"])
    item.append(line["user id"])
    item.append(line["Amount"])
    item.append(line["Transaction Date"])
    item.append(line["FIrst Transaction"])
    line_items.append(item)
if __name__ == "__main__":
with open("ChurnTest.csv") as f_obj:
    csv_dict_reader(f_obj)

def dateSplit():
for i in range(1,4192):
    line = line_items[i]
    amount = line_items[i][2]
    if len(amount) > 1 and line_items[i][1] == '114769':
        if float(amount) > 150:
                line_items[i][2] = float(amount) / 12
                #monthly_transactions.append(line_items[i])
                year = int(line[3][:2])
                month = int(line[3][4:])
                for x in range(11):
                    month = int(month)            
                    year = int(year)
                    newLine = line_items[i]
                    if month > 11:
                        year = year + 1
                        month = 1
                    else:
                        month = month + 1
                    newLine[3] = str(year) + "-" + str(month)
                    annualized.append(newLine)
                    #This prints out the data as I want it to be
                    print(annualized[len(annualized)-1])
        else:
            monthly_transactions.append(line_items[i])

dateSplit()
#This prints out the data incorrectly.
print(annualized)

1 个答案:

答案 0 :(得分:0)

您对错误的来源是正确的,它在循环for x in range(11):中。这一行:

 newLine = line_items[i]

创建新对象。 Python列表是可变的,因此即使在您编辑它之后,newLine仍然引用annualizedline_items中的相同对象。最小的修复是:

newLine = line_items[i][:] # or 'line[:]' - see below

使newLine成为每个循环的单独副本。

您可能应该阅读thisthis以获取有关名称和参考的更多信息。

为什么要分配line然后继续引用line_items[i]?此外,硬编码4192似乎很奇怪;你不能做for line in line_items[1:]:吗?