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

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

我如何計算字典中每個標題的數量

我如何計算字典中每個標題的數量

嚕嚕噠 2021-12-21 17:42:08
我一直試圖弄清楚它有一段時間了,而不是最擅長編程。這是我到目前為止所擁有的。字典的鍵應該是列表中員工的頭銜,值是具有該特定頭銜的員工數。employees = [    {        "email": "[email protected]",        "employee_id": 101,        "firstname": "Jonathan",        "lastname": "Calderon",        "title": "Mr",        "work_phone": "(02) 3691 5845"    },    {        "email": "[email protected]",        "employee_id": 102,        "firstname": "Christopher",        "lastname": "Hansen",        "title": "Mr",        "work_phone": "(02) 5807 8580"    },    {        "email": "[email protected]",        "employee_id": 103,        "firstname": "Isabella",        "lastname": "Dorsey",        "title": "Mrs",        "work_phone": "(02) 6375 1060"    },    {        "email": "[email protected]",        "employee_id": 104,        "firstname": "Barbara",        "lastname": "Baker",        "title": "Ms",        "work_phone": "(03) 5729 4873"    }]#my workfor i in employees:    print(i['title'])employees.count('title')print()#my output:MrMrMrsMs#expected output:{'Ms': 1, 'Mrs': 1, 'Mr': 2}
查看完整描述

3 回答

?
胡子哥哥

TA貢獻1825條經驗 獲得超6個贊

collections.Counter


from collections import Counter


counts = Counter([x['title'] for x in employees])

print(counts)

# Counter({'Mr': 2, 'Mrs': 1, 'Ms': 1})

如果有任何沒有title字段的記錄,請使用:


counts = Counter([x.get("title", None) for x in employees])

# Counter({'Mr': 2, 'Mrs': 1, 'Ms': 1, None: 1})

在這里,如果不存在,.get將獲取title或返回的值。Nonetitle


查看完整回答
反對 回復 2021-12-21
?
呼啦一陣風

TA貢獻1802條經驗 獲得超6個贊

使用 collections.defaultdict


前任:


from collections import defaultdict


result = defaultdict(int)

for i in employees:

    result[i["title"]] += 1

print(result)

輸出:


defaultdict(<type 'int'>, {'Mrs': 1, 'Ms': 1, 'Mr': 2})


查看完整回答
反對 回復 2021-12-21
?
米琪卡哇伊

TA貢獻1998條經驗 獲得超6個贊

你可以用一個計數器來做到這一點:


from collection import Counter

titles = [e['title'] for e in employees]

counts = Counter(titles)

# Counter({'Mr': 2, 'Mrs': 1, 'Ms': 1})


查看完整回答
反對 回復 2021-12-21
  • 3 回答
  • 0 關注
  • 160 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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