简体   繁体   English

如果第一个值匹配,则求和值

[英]Sum Values If First Values Match

Is there any way i can compare both lists and sum the second value ONLY if the the first value matches?有什么方法可以比较两个列表并仅在第一个值匹配时才对第二个值求和? I queried two tables and gave me the results below but not sure if python has some sort of group function i can use to group the account number(first value) and sum the second values if the first value matches.我查询了两个表并给出了下面的结果,但不确定 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')

example例子

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

output输出

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

Is there any way i can compare both lists and sum the second value ONLY if the the first value matches?有什么方法可以比较两个列表并仅在第一个值匹配时才对第二个值求和?

Yes:是的:

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

使用列表理解

[(i[0],i[1]+j[1]) for i,j in zip(list1,list2) if i[0]==j[0]]

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

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