簡體   English   中英

請問我如何總結sqlite3表行中的所有整數元素

[英]Please how do i sum up all the integer elements from a sqlite3 table row

我想使用來自sqlite3數據庫表的用戶數據來計算一行元素的總和

我使用cursor.fetchall()獲取數據庫表中的金額行,並嘗試使用for循環求和表中的元素,但出現錯誤

db = sqlite3.connect('my.db')
cursor = db.cursor()
cursor.execute('SELECT amount FROM expenses')
result = cursor.fetchall()
c = 0
for x in result:
    c += x
print(c)

我收到TypeError:+ =不支持的操作數類型:'int'和'tuple'我希望得到金額的總和

我知道sqlite3 SUM命令。 但我想學習如何使用Tkinter解決此問題

采用

c = 0
for x in result:
    c += x[0]

cursor.fetchall()返回一個元組列表,該元組包含每行的列值。 在您的情況下,碰巧只有一列,但它仍然是(一個元素)元組。

據我所知,cursor.fetchall()返回一個元組(如您的錯誤告訴您),這意味着您對sql查詢的所有選擇都將被推入該元組。

例如,如果要選擇多個列:

'SELECT amount, tax, date FROM expenses' 

您將檢索到這樣的元組:

(amount, tax, date)

每行都給出該元組。 在您的情況下,結果是一個包含所有行的數組,其中每一行本身都是一個元組,其中只有數量。

長話短說,您要么需要將結果重建為具有列表理解的列表,例如:

db = sqlite3.connect('test.db')
cursor = db.cursor()
cursor.execute('SELECT amount FROM expenses')
result = cursor.fetchall()

result = [amount[0] for amount in result] # Rebuild your result array to contain 
                                          # single values instead of tuples
c = 0
for x in result:
    c += x
print(c)

另一個解決方案是:

db = sqlite3.connect('test.db')
cursor = db.cursor()
cursor.execute('SELECT amount FROM expenses')
result = cursor.fetchall()
c = 0
for x in result:
    c += x[0] # This will retrieve the 0th element from the tuple, which is the amount
print(c)

使用Python內置的sum()doc )函數:

c = sum(i[0] for i in result)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM