2012-08-03 47 views
1

Python初學者正在運行2.7Python:附加到'int'函數的解決方法

我想要一個列表,它會隨着新值的添加而不斷總結。但是,我不斷收到屬性錯誤:'int'對象沒有'追加'功能。我瞭解基本問題 - 您不能附加到整數 - 但希望找到解決方法。你們有沒有解決方案?

我的代碼的簡化版本,然後我想避免一個可能的解決方案。

my_list = sum([]) 

def myfunction (i): 
    return i 

thing = myfunction (1) 
my_list.append(thing) 

thing2 = myfunction (2) 
my_list.append(thing2) 

def function_2 (a,b): 
    #function which uses my_list 

我想我可以做下面的解決方案,但我想避免它(干擾現有的代碼)。

my_list = [] 
summed_my_list = sum (mylist) 

def myfunction (i): 
    return i 

thing = myfunction (1) 
my_list.append(thing) 

thing2 = myfunction (2) 
my_list.append(thing2) 
+0

你是什麼意思 「的值被添加到它不斷地總結出」 呢?這聽起來像你要麼追蹤名單和總結價值,要麼只是總結價值 - 這是什麼? – jmetz 2012-08-03 19:03:07

+1

你根本不可能有一個單一的變量都是列表和一個列表的總和。你將不得不創建一個自定義的數據類型,或者有兩個變量浮動。 您的「拒絕解決方案」如何幹擾現有代碼? – 2012-08-03 19:05:47

+0

只有總和值很重要。 – user1569317 2012-08-03 19:07:42

回答

1

如果您不需要列表中的問題是微不足道的,因爲你只需要

total += value 

在每一個步驟。

類從列表

衍生如果確實需要兩個列表,總和(其中自動更新),你可以創建一個從列表中衍生而來,例如一類 - 這應該自動求和,當你追加到它。

class mylist(list): 
    tot = 0 
    def append(self, value): 
     super(mylist, self).append(value) 
     self.tot += value 

用法示例

#!/usr/bin/python 

class mylist(list): 
    tot = 0 
    def append(self, value): 
    super(mylist, self).append(value) 
    self.tot += value 


a = mylist() 
a.append(1) 
a.append(20) 
print a.tot 
print a 

輸出:

21 
[1,20] 
0

這條線是你的問題:

my_list = sum([]) 

這將返回整數0。剛剛初始化您的清單:

my_list = [] 

並追加到。

如果你也想保持一個運行總計,有總另一個變量:

my_total = 0 

my_total += new_number 

而且有一個單一的方法,將新的整數增加總把它們添加到列表中。