python对我来说是一门新语言,所以这个问题听起来可能很简单,但如果有人能给我指明正确的方向,我将不胜感激!我创建了一个名为employees的字典,它包含了关于它们的一些值:
我试着读出每个部门有多少人,例如:技术-2,会计-1。
我有类似的东西,但打印出来是空白的。
def main():
employees= {'name': 'John', 'empID': '102', 'dpt': 'tech', 'title':
'programmer', 'salary': '75'}
{'name': 'Jane', 'empID': '202', 'dpt': 'tech', 'title': 'programmer',
'salary': '80'}
{'name': 'Joe', 'empID': '303', 'dpt': 'accounting', 'title':
'accountant', 'salary': '85'}
for item in employees:
dic = employees[item]
if dic['dpt'[0]]==dic['dpt'[1]]:
duplicate += 1
print("there are "+ duplicate)
else:
print("There are no duplicate")
发布于 2018-06-01 15:01:46
如果您不想导入Counter
,请使用字典来跟踪每个部门的员工数量:
employee_list = [{
'name': 'John',
'empID': '102',
'dpt': 'tech',
'title': 'programmer',
'salary': '75'
}, {
'name': 'Jane',
'empID': '202',
'dpt': 'tech',
'title': 'programmer',
'salary': '80'
}, {
'name': 'Joe',
'empID': '303',
'dpt': 'accounting',
'title': 'accountant',
'salary': '85'
}]
department_to_count = dict()
for employee in employee_list:
department = employee["dpt"]
if department not in department_to_count:
department_to_count[department] = 0
department_to_count[department] += 1
for department, employee_count in department_to_count.items():
print("Department {} has {} employees".format(department,
employee_count))
发布于 2018-06-01 15:02:11
from collections import Counter
employees = [{'name': 'John', 'empID': '102', 'dpt': 'tech', 'title': 'programmer', 'salary': '75'},
{'name': 'Jane', 'empID': '202', 'dpt': 'tech', 'title': 'programmer', 'salary': '80'},
{'name': 'Joe', 'empID': '303', 'dpt': 'accounting', 'title': 'accountant', 'salary': '85'}]
dpts = [x['dpt'] for x in employees]
print(Counter(dpts))
# Counter({'tech': 2, 'accounting': 1})
发布于 2018-06-01 15:35:02
如果您正在寻找一个特定关键字的合计,您可以使用.count()
list method作为直接查询。
给出一个字典列表:
>>> employees = [{'name': 'John', 'empID': '102', 'dpt': 'tech', 'title': 'programmer', 'salary': '75'},
{'name': 'Jane', 'empID': '202', 'dpt': 'tech', 'title': 'programmer', 'salary': '80'},
{'name': 'Joe', 'empID': '303', 'dpt': 'accounting', 'title': 'accountant', 'salary': '85'}]
您可以使用列表理解创建每种类型的列表:
>>> [d['dpt'] for d in employees]
['tech', 'tech', 'accounting']
然后这就可以被记录下来:
>>> [d['dpt'] for d in employees].count('tech')
2
>>> [d['dpt'] for d in employees].count('accounting')
1
>>> [d['dpt'] for d in employees].count('nothing')
0
或者,您可以构造一个生成器来计算特定值:
>>> sum(1 for d in employees if d['dpt']=='tech')
2
如果您想要获得所有元素的计数(而不是使用计数器),您可以这样做:
>>> lot=[d['dpt'] for d in employees]
>>> {c:lot.count(c) for c in set(lot)}
{'accounting': 1, 'tech': 2}
https://stackoverflow.com/questions/50637701
复制相似问题