简体   繁体   English

从Python SQLite3查询中求和

[英]Summing numbers from a Python SQLite3 Query

I would like to do some math with numbers I have stored in an SQLite database. 我想用我存储在SQLite数据库中的数字做一些数学运算。 My query seems to work. 我的查询似乎有效。 My issue is having python treat the numbers that I have queryed from the database as numbers. 我的问题是让python将我从数据库查询的数字视为数字。

The first definition selects a unique row from my database. 第一个定义从我的数据库中选择一个唯一行。 The second definition cycles thru a number of rows in my database and adds them to a list of numbers which I would like to sum. 第二个定义遍历数据库中的许多行,并将它们添加到我要求和的数字列表中。

The problem occurs when I try to sum the numbers. 当我尝试对数字求和时会出现问题。 Can anyone point me in the right direction? 谁能指出我正确的方向?

Here is some of my code: 这是我的一些代码:

def query_symbol(symbolId):
    uniqueId = str(symbolId) + '@' + str(datetime.date.today())

    conn = sqlite3.connect('sql/databse.db')
    c = conn.cursor()
    with conn:
        c.execute("SELECT number FROM symbols WHERE uniqueId= ?", (uniqueId,))
    return c.fetchall()

def calc(filename):
    symbolIds = def_sec.load_symbolIds(filename)

    print(len(symbolIds))

    list = []

    for symbolId in symbolIds:
        data = query_symbol(symbolId)
        #data = data.replace('()','')
        list.append(data)
    print(list)

        total = sum(list)
        print(total)

calc('index_symbolids')

My error message looks like this: 我的错误消息如下所示:

65
[[(13506636000.0,)], [(20156784500.0,)], [(21361120000.0,)], [(4650564600.0,)], [(18572773200.0,)], [(13889340000.0,)], [(21911477100.0,)], [(19014765000.0,)], [(8592582800.0,)], [(12399850600.0,)], [(26021607500.0,)], [(17344514400.0,)], [(28396342200.0,)], [(10444843100.0,)], [(13894385900.0,)], [(26429184100.0,)], [(9193019800.0,)], [(18356516200.0,)], [(13693344800.0,)], [(39135783700.0,)], [(64988933000.0,)], [(52588381800.0,)], [(53514752300.0,)], [(8205312900.0,)], [(18563139800.0,)], [(34542681400.0,)], [(10626282600.0,)], [(14568874300.0,)], [(52083201800.0,)], [(21204153700.0,)], [(13380654000.0,)], [(24821311300.0,)], [(8232241800.0,)], [(148515191500.0,)], [(31669795700.0,)], [(97989223400.0,)], [(135145143799.0,)], [(178696200.0,)], [(9474728600.0,)], [(77661549000.0,)], [(33649778800.0,)], [(10061871500.0,)], [(23682872900.0,)], [(5196629500.0,)], [(54706667400.0,)], [(13934478600.0,)], [(5141383100.0,)], [(81343002200.0,)], [(16173162200.0,)], [(17649907400.0,)], [(32514907200.0,)], [(9783995600.0,)], [(75825589800.0,)], [(6205111500.0,)], [(53908007900.0,)], [(7615559400.0,)], [(17484345800.0,)], [(16072715900.0,)], [(53990182900.0,)], [(25798084100.0,)], [(28311485300.0,)], [(7296894200.0,)], [(19297000000.0,)], [(13271169800.0,)], [(22862203000.0,)]]
Traceback (most recent call last):
  File "/Users/michael/atomProjects/calc.py", line 53, in <module>
    index_calc('index_symbolids')
  File "/Users/michael/atomProjects/calc.py", line 49, in calc
    total = sum(list)
TypeError: unsupported operand type(s) for +: 'int' and 'list'
[Finished in 0.822s]

The problem occurs when I try to sum the numbers. 当我尝试对数字求和时会出现问题。

No, you are trying to sum list of lists. 不,您正在尝试对列表列表求和。

total = sum(map(lambda x: x[0][0], list)

Also, you should avoid using list as a variable because it shadows the builtin list . 另外,您应该避免将list用作变量,因为它会遮盖内置的list

I saw two problems. 我看到了两个问题。 Let's take a look at your list which you printed out: 让我们看一下您打印出的list

[[(13506636000.0,)], [(20156784500.0,)],  ... ]

What it told me is you have a list of nested lists (eg [(13506636000.0,)] ). 它告诉我的是您有一个嵌套列表的列表(例如[(13506636000.0,)] )。 This represents the a single row and a single column, because you return c.fetchall() . 因为您返回c.fetchall() ,所以它表示单行和单列。 In this case, you know for sure that at most 1 row of data is returned, so we can use c.fetchone() to reduce the number of nested lists. 在这种情况下,您可以确定最多返回1行数据,因此我们可以使用c.fetchone()减少嵌套列表的数量。

Next, take a look at this line: 接下来,看看这一行:

        data = query_symbol(symbolId)

Since c.fetchone() returns (13506636000.0,) , which is a tuple of 1 element, you can use the following trick to extract the number: 由于c.fetchone()返回(13506636000.0,) (这是1个元素的元组(13506636000.0,) ,因此您可以使用以下技巧来提取数字:

        (data,) = query_symbol(symbolId)

Putting it together: 把它放在一起:

def query_symbol(symbolId):
    uniqueId = '{}@{}'.format(symbolId, datetime.date.today())

    with sqlite3.connect('sql/database.db') as conn:
        c = conn.execute(
            "SELECT number FROM symbols WHERE uniqueId=?",
             (uniqueId,))
    return c.fetchone()

def calc(filename):
    symbolIds = def_sec.load_symbolIds(filename)

    print(len(symbolIds))

    numbers = []

    for symbolId in symbolIds:
        (data, ) = query_symbol(symbolId)  # instead of `data =`
        numbers.append(data)

    print(numbers)
    total = sum(numbers)
    print(total)

calc('index_symbolids')

At this point, you should get the desired result. 在这一点上,您应该得到期望的结果。

Update 更新资料

This update explains how (data,) = works. 此更新说明(data,) =工作方式。 Let say, if you have a tuple of 3 elements and want to assign to variables a , b , c : 假设,如果您有一个由3个元素组成的元组,并且想要分配给变量abc

(a, b, c) = (1, 2, 3)  # a=1, b=2, c=3

In practice, we can drop the parentheses from the left side of the equal sign: 实际上,我们可以从等号的左侧删除括号:

a, b, c = (1, 2, 3)  # a=1, b=2, c=3

For a 1-element tuple, the notation is (1,) , not (1) (which is simply 1 ): 对于1元素元组,表示法是(1,) ,而不是(1)(简单地是1 ):

data = (1,)     # data = (1,), which is the whole tuple
(data,) = (1,)  # data = 1, which is what we want
data, = (1,)    # data = 1, but the syntax looks kind of wrong

Back to your problem, the function query_symbol() returns a 1-element tuple, thus we have to use: 回到您的问题,函数query_symbol()返回一个1元素的元组,因此我们必须使用:

(data,) = query_symbol(symbolId)
data, = query_symbol(symbolId)

I personally like the first syntax because the second looks like the comma was there by a mistake. 我个人喜欢第一种语法,因为第二种语法看起来像是逗号,是一个错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM