Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the comprehensive applications of Python dict

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

本篇内容主要讲解"Python dict的综合应用有哪些",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"Python dict的综合应用有哪些"吧!

题目1 写一个程序,合并字典里面相同 key 的值。

输入:

d1 = {'a': 100, 'b': 200, 'c':300} d2 = {'a': 300, 'b': 200, 'd':400}

输出:

{'a': 400, 'b': 400, 'd': 400, 'c': 300}

2 写一个程序,打印出字典里面所有唯一的值。

输入:

[{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"}, {"VII":"S005"}, {"V":"S009"},{"VIII":"S007"}]

输出:

{'S005', 'S002', 'S007', 'S001', 'S009'}

3 把字典中的值分别取出,打印出不同字母的排列组合。

输入:

{'1':['a','b'], '2':['c','d']}

输出:ac ad bc bd

解答1

这个题目,可以用循环+判断的方式,一个个的把值加起来,但是有点麻烦,直接用 Python 里面一个内置的模块可以轻松搞定。

from collections import Counter

d1 = {'a': 100, 'b': 200, 'c':300}

d2 = {'a': 300, 'b': 200, 'd':400}

d = Counter(d1) + Counter(d2)

print(dict(d)) 2

这个题目,可以记住 DE8UG 的小提示,只要是涉及到唯一值的,很多都可以用 set 的排重的特点去完成。比如,这里只需要先把字典循环,然后取到每个字典的值,最后用 set 把重复的值取出,搞定。

L = [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"}, {"VII":"S005"}, {"V":"S009"},{"VIII":"S007"}]

print("Original List: ", L)

u_value = set( val for dic in L for val in dic.values())

print("Unique Values: ", u_value) 3

这题目可以有两个做法。一个是直接取到字典里的所有值,转换成列表,然后分别循环每个列表,把相应的字母相加即可。

d = {'1': ['a', 'b'], '2': ['c', 'd']}

la, lb = list(d.values())

print(la, lb)

print([(x+y) for x in la for y in lb])

另一个做法是使用 python 的 itertools,用里面的 product 方法直接去自动计算,其实内部和上一段代码的双层 for 循环实现方法类似。注意查看官方文档,参数位置需要一个星号。

import itertools

d = {'1': ['a', 'b'], '2': ['c', 'd']}

print(list(d.values()))

for combo in itertools.product(*list(d.values())):

print(''.join(combo))到此,相信大家对"Python dict的综合应用有哪些"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report