【问题标题】:How to subtract values from two functions in python如何从python中的两个函数中减去值
【发布时间】:2017-08-17 15:55:38
【问题描述】:

我有两个 sqlite 表,其中都包含不同的项目及其数量。我要做的是遍历第一个表,从第一个表中选择数量,然后从第二个表中项目名称匹配的数量中减去它。

(表1)

项目 |数量 ---------- 糖| 50 笔 | 10 苹果| 高分辨率照片| CLIPARTO 50 浆果 | 1

第二个表(由用户输入填充)(表2)

项目 |数量 ---------- 糖 |500 笔 |5 苹果|8 浆果 |1

正如我所说,我想遍历表 1 并从表 1 中获取糖的数量。然后遍历表 2 并获取表 2 中的糖量,最后减去这些值并返回减法后的值。然后对table1中的其他项目做同样的事情。(循环)

例如使用糖, (表 2 中的糖量 - 表 1 中的糖量) (500 – 50) = 450 然后它返回值 450 以便我可以在其他函数中使用它

代码示例。

import sqlite3

db = sqlite3.connect('example.db')
#db.execute('create table Table1 (items text, quantity integer)')
#db.execute('create table Table2 (items text, quantity integer)')
a = 'Sugar'
b = 50
c = 500
db.execute('insert into Table1 (items, quantity) values(?,?)',(a, b))
db.execute('insert into Table1 (items, quantity) values(?,?)',(a, c))
db.commit()
db.close()

def one():
    cursor = db.execute('select items from Table1')
    for i in cursor.fetchall():
        return i

def two():
    cursor1 = db.execute('select quantity from Table1 where items = ?',(one()))
    for i in cursor1.fetchall():
        return i

def three():
    cursor1 = db.execute('select quantity from Table2 where items = ?',(one()))
    for i in cursor1.fetchall():
        return i

def subtraction():
    t = three() - two()
    return t

运行上述代码时出现的错误 文件“C:/Users/MegaMind/Documents/Programming/Pycham Projects/New folder/package.py”,第 22 行,减法 t = 三() - 二() TypeError: 不支持的操作数类型 -: 'tuple' 和 'tuple'

如果有更简洁的方法可以做到这一点,请尽你所能提供帮助。

【问题讨论】:

标签: python database python-3.x sqlite


【解决方案1】:

您可以简单地告诉数据库连接两个表:

cursor = db.execute('''SELECT items, Table2.quantity - Table1.quantity
                       FROM Table1
                       JOIN Table2 USING (items)''')
for row in cursor:
    name = row[0]
    diff = row[1]
    ...

【讨论】:

    【解决方案2】:

    你做得太难了。 SQL 可以自己做到这一点,并在银盘中为您提供结果:

    SELECT table1.items, table1.quantity - table2.quantity as remaining 
    FROM table1 LEFT JOIN table2 ON table1.items = table2.items
    

    LEFT JOIN 确保table1 的所有行都将出现在结果中。如果您只想减少计数,请使用普通的JOIN

    【讨论】:

    • 彼得,请点击旁边的大勾号“接受”您最喜欢的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 1970-01-01
    • 2014-11-22
    • 2017-09-29
    • 1970-01-01
    • 2013-01-29
    相关资源
    最近更新 更多