亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何確保使用 for 循環和 try except 在 Python 字典中創建正確的鍵:值對?

如何確保使用 for 循環和 try except 在 Python 字典中創建正確的鍵:值對?

MYYA 2023-10-18 15:46:32
在將元素添加回字典時,我嘗試執行下面的粗體行,但我想確保它正在執行我想要的操作。我也將 csv 文本放在底部。我想確保,如果相同的收入類型出現多次,我的函數將能夠捕獲它,并且我的函數會通過下面的 try 和 except 忽略缺少或無效金額的收入。迭代列表中的每一行for line in lines:    # strip white spaces in the line    line = line.strip()    # split items in the line by :    income_list = line.split(':')    # if empty amount, skip the line    if len(income_list) <= 1:        continue    # set the type and amount as a variable and strip white space    income_type = income_list[0].strip()    total_income_amount = income_list[1].strip()    # try and except to catch invalid amount    try:        total_income_amount = float(total_income_amount)                **#add income type and amount to income dictionary**         income[income_type] = income.get(income_type, 0) + total_income_amount    except ValueError:        continue如果這是 csv 中的收入列表:但我們希望能夠根據輸入的費用類型對其進行排序。股票:10000 房地產:2000 工作:80000 投資:30000 股票:20000 投資:1000 捐贈:合同:sss感謝您的幫助!
查看完整描述

1 回答

?
慕桂英546537

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"])


查看完整回答
反對 回復 2023-10-18
  • 1 回答
  • 0 關注
  • 112 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號