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)
解决方案
有什么方法可以比较两个列表并仅在第一个值匹配时对第二个值求和?
是的:
if list1[0] == list2[0]:
result = list1[1] + list2[1]
推荐阅读
- amazon-s3 - 使用Snowflake自带的原生stage相比有S3作为stage area有什么缺点
- linux - Unison 失败:未捕获的异常失败(“input_value:格式错误的消息”)
- php - 未定义索引:第30行/storage/ssd1/900/12273900/public_html/upload_image.php中的 faceId
- r - R - 将 Dataframe 子集到所有可能的组合中
- facebook - 在 Spark AR Studio 中使用本机 UI 选择器在双语过滤器中切换语言
- xslt - XSLT 1.0 - 在 sum 之前格式化数字
- c# - 如何在 Identity 3.1 中自定义用户?
- arangodb - arango shell 不包含在 ArangoDB 3.6.3 for macos 中
- ruby-on-rails - 在不触摸/保存标记记录的情况下修改作为可标记的标记
- neo4j - 如何使用 Neo4j 变量,不使用变量/标识符的查询行为不同