有一个需求是要统计一个列表中每个元素出现的次数 并且将这个元素作为键 元素出现的次数作为值 重新组成一个新的字典对象 将如何做
这里用到的知识点如下
1、dict.update 更新字典的键值对
2、count函数 统计元素出现的次数
3、for循环 用来遍历
代码
demo_list [ python , php , java , python ]
demo_dict {}
for item in demo_list:
demo_dict.update({item: demo_list.count(item)})
print(demo_dict)
运行结果
{ python : 2, php : 1, java : 1}
Process finished with exit code 0
有兴趣加入测试交流群 欢迎测开爱好者加入我们~



