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

时间:2020-03-03 19:14:37

标签: python

有什么方法可以比较两个列表并仅在第一个值匹配时对第二个值求和吗?我查询了两个表,并给了我下面的结果,但不确定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)

2 个答案:

答案 0 :(得分:1)

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

是:

abstract class AFruit{
   isBad:boolean;
}

class Apple extends AFruit {}
class Orange extends AFruit {}

//problem
interface Storage
{
   fruit: type-base-of-abstract-fruit; //this is what I'd like to figure out
}

//my version
interface Storage
{
   fruit: typeof Apple | typeof Orange;
}


//finally, my example usage:
{fruit: Apple}
//or
{fruit: Orange}

答案 1 :(得分:1)

使用列表理解

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