1 回答
TA贡献1848条经验 获得超10个赞
records = [] # for storing line data
for line in lines:
# Need to split correctly first.
income_list = line.strip().replace(": ", ":").split(" ") # ['stock:10000', 'estate:2000', ...]
# loop over each income data of the line
income = {}
for i in income_list:
# get type and amount
income_type, income_amount = [tmp.strip() for tmp in i.strip().split(":")]
# try if the value is valid
try:
if income_type not in income.keys():
income[income_type] = float(income_amount)
else:
income[income_type] += float(income_amount)
except:
continue
# save this line data to the records
records.append(income)
# do your sorting here as needed with 'records'
# keep in mind not all data have the same keys
# so you need to deal with null key values
# for example assuming all data has the key "stock"
sorted_by_stock_asc = sorted(records, key=lambda x: x["stock"])
添加回答
举报