用Python对列表求和

2024-09-30 20:27:43 发布

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

我已经从CSV文件中导入了值,该文件在第1列中有日期,在第2列中有美元值。我打开它,计算了每行每月的变化。这些更改mthchangeprofit已附加到列表monthlychange

我想用monthlychange的和除以count(6)来计算平均月变化。我已将monthlychange转换为名为sum_mthlyfloat。平均变化应计算为-450美元/6=-75美元。数据文件中不存在C列和D列。为了便于比较,我将它们添加到图像中

testdata

两个问题:

  1. sum_mthly正在获取上一个月的变化,而不是将整个列表相加

  2. 尽管是integer,但如果没有“浮点零除错误”,我不能用countofchanges替换数字6。它打印出“6”

    # Open the CSV.
     with open(file, newline="") as csvfile:
         csvreader = csv.reader(csvfile, delimiter=",")
         csvheader = next(csvreader)
    
     # Initialize variables as zero.
     count = 0
     beginprofit = 0
    
     # Conducting the ask
     for row in csvreader:    
     #Count the number months.
     count = count + 1 
    
     # Create data lists to append data rows to.
     monthlychange = []
    
     #Calculate the monthly change in profits.
     endprofit = int(row[1])
     mthchangeprofit = endprofit - beginprofit
    
     #Store these monthly changes in a list
     monthlychange.append(mthchangeprofit)
    
     beginprofit = endprofit
    
     #Calculate the avg change in profits
     countofchanges = count - 1        #denominator
     sum_mthly = sum(float(mthchangeprofit) for mthchangeprofit in monthlychange)  #numerator
    
     avgchange_profits = sum_mthly/6  #only using last mthly change
    
     print(type(mthchangeprofit))      #integer
     print(type(monthlychange))        #list
     print(type(sum_mthly))            #float
     print(type(countofchanges))       #integer   
     print("----------------------------------------------------------")
     print("Count of Changes: " + str(countofchanges))        #prints "6"
     print("Average Change: " + "$" + str(int(avgchange_profits)))   #prints "$16"
    

Tags: theintypecountintegerfloatsumprint