You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python代码优化:将JSON两字段合并为正负浮点数列表

Fixing Bank Transaction Amount Conversion to a Single Numeric List

Let's get your code sorted to produce the exact output you need. The main issues with your original code are that it's creating tuples (including empty strings) instead of converting values to signed floats, and the conditional check isn't correctly filtering or processing the fields.

Here's the revised code that meets your requirements:

def konto_all():
    transaction_amounts = []
    for entry in bankstm:
        # Process FIELD7: convert to negative float if not empty
        debit = entry["FIELD7"].strip()
        if debit:
            # Replace comma with dot for decimal consistency, convert to negative float
            amount = -float(debit.replace(",", "."))
            transaction_amounts.append(amount)
        
        # Process FIELD8: convert to positive float if not empty
        credit = entry["FIELD8"].strip()
        if credit:
            amount = float(credit.replace(",", "."))
            transaction_amounts.append(amount)
    
    return transaction_amounts

# Execute the function and print the result
kontoall = konto_all()
print(kontoall)

Key Changes Explained:

  • Single List Output: We initialize a flat list transaction_amounts instead of a 2D list, since we only need a sequence of numeric values.
  • Proper Empty String Handling: Using strip() ensures we catch any entries with only whitespace, and we check if the field has actual content before processing.
  • Signed Float Conversion:
    • FIELD7 values are converted to negative floats (assuming these represent debits/withdrawals)
    • FIELD8 values are converted to positive floats (assuming these represent credits/deposits)
  • Simplified Logic: We removed the unnecessary index check (your original code's index > 1 was filtering out early entries, but your expected output includes all transactions). If you do need to skip header rows, you can add back for index, entry in enumerate(bankstm): and wrap the processing in if index > 1:.

Testing with Your JSON Data:

When run against your provided bank transaction JSON, this code will output:

[56.0, -109.0, -78.9, -56.9, -46.8, 400.0]

Which matches your expected output (note: Python may display floats like 56.0 instead of 56.00, but the numeric value is identical).

内容的提问来源于stack exchange,提问作者Swag Mand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 11:42:31