Python二维数组常用方法汇总

Python二维数组常用方法汇总

 1、字段类型转换

#将数量、金额等字符串转换为数字
floatcolumns = {16,25}  # 需要转换为float的列索引
for row in listSource:
    for i in floatcolumns:
        # 确保数量是数值类型
        try:
            row[i] = float(row[i])
        except ValueError:
            row[i] = 0  # 如果转换失败,设为0

2、筛选、汇总求和

atotal=0.0
# 筛选
aresult=[
    aitem for aitem in listSource 
    if aitem[10] == "收据" 
]
if len(aresult)>0:
    atotal = sum(aitem[16] for aitem in aresult)

#筛选  
bresult=[
    bitem for bitem in listSource 
    if bitem[9] in ("折扣", "毛保") and bitem[10] == "供应商" 
]

3、按物料编码分组求和

#按商品编码分组求和
grouped = {}
for row in bresult:
    
    # 提取分组键
    key = (
        row[20],  # 物料编码
    )
    
    # 如果键已存在,则累加数量和金额
    if key in grouped:
        grouped[key][25] += row[25]  # 数量累加
        grouped[key][16] += row[16]  # 含税金额累加
    else:
        grouped[key] = row.copy()  # 创建新条目

# 返回分组后的结果
groupList = list(grouped.values())

4、按单据编号分组形成主从表结构,生成主从表结构的JSON数据结构

from collections import defaultdict

# 使用defaultdict按单据编号分组
grouped_data = defaultdict(list)

for item in excelList:
    billno = str(item[0])
    grouped_data[billno].append(item)
    
# 构建最终的JSON结构
jsonList = []

    
for billno, items in grouped_data.items():
        
     
    # 单据体信息
    body = []
    for item in items:
        body_item = {
            "e_material": str(item[40]), #物料编码
            "e_measureunit": str(item[41]), #计量单位
            "e_quantity": round(float(item[43]),2), #数量
            "e_unitprice": round(float(item[45]),6), #单价
            "e_taxrate": float(item[47]),  #税率
            "e_taxunitprice": round(float(item[48]),6), #含税单价
            "e_amount": round(float(item[52]),2), #金额
            "e_tax": round(float(item[54]),2), #税额
        }
        body.append(body_item)
        
    # 添加到结果中
    jsonList.append({
        "billno": str(items[0][0]), #单据编号
        "billtype": str(items[0][2]), #单据类型
        "bizdate": str(items[0][3]), #单据日期
        "currency": str(items[0][16]), #结算币
        "exchangerate": float(items[0][19]), #汇率
        "cqkd_customer": str(items[0][35]), #门店档案
        "entry": body
    })

 

posted @ 2025-06-16 16:27  中国结  阅读(16)  评论(0)    收藏  举报