首页 > 解决方案 > 如果第一个值匹配,则求和值

问题描述

有什么方法可以比较两个列表并仅在第一个值匹配时对第二个值求和?我查询了两个表并给了我下面的结果,但不确定 python 是否有某种组函数,我可以使用它来对帐号(第一个值)进行分组,如果第一个值匹配,则对第二个值求和。

import psycopg2

def connect():
    conn = psycopg2.connect(host="test", port=5432, database="test", user="test", 
    password="test123")
    cursor = conn.cursor()
    return cursor

def allocation(cursor,cashdt, sumbmaster):
    alloclist = []
    print("Allocation: ")
    cursor.execute("""select bill_acct,sum(debit_amount) from test.a where 
    cash_date ='"""
               + cashdt + "'" + "and master_bill='" + sumbmaster +"' group by bill_acct")
    for row in cursor.fetchall():
         a = row[0],"{:.2f}".format(row[1])
         alloclist.append(a)
     print(alloclist)

 def statement(cursor, billingdt,sumbmaster):
     statementlist = []
     cursor.execute(
         """
         select bill_account,total_due_amount from test.b where billing_date ='""" 
     + billingdt + "'" + "and master_bill='" + sumbmaster + "'")
     print("Statement:")
    for row in cursor.fetchall():
         a = row[0], "{:.2f}".format(row[1])
         statementlist.append(a)
     print(statementlist)

def main():
    connect()
    allocation(connect(),'2020-02-25','123')
    statement(connect(), '2020-2-14', '345')

例子

list 1 =[('123',1),('345', 2)]
list2 = [('123',1),('345', 2)]

输出

('123',2), ('345',4)

标签: python

解决方案


有什么方法可以比较两个列表并仅在第一个值匹配时对第二个值求和?

是的:

if list1[0] == list2[0]:
    result = list1[1] + list2[1]

推荐阅读