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_amountsinstead 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
indexcheck (your original code'sindex > 1was filtering out early entries, but your expected output includes all transactions). If you do need to skip header rows, you can add backfor index, entry in enumerate(bankstm):and wrap the processing inif 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
相关产品推荐
相关产品推荐

