1、列表推导式
1.1、求0~29之间能被3整除的数
ret = [i for i in range(30) if i%3 ==0] print(ret)
输出结果:
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
2、字典推导式
2.1、将字典mcase = {‘a‘: 10, ‘b‘: 34}的key、value互换位置
mcase = {‘a‘: 10, ‘b‘: 34} mcase_frequency = {mcase[k]: k for k in mcase} print(mcase_frequency)
输出结果:
{10: ‘a‘, 34: ‘b‘}
2.2、将字典中大小写key的value值相加
mcase = {‘a‘: 10, ‘b‘: 34, ‘A‘: 7, ‘Z‘: 3} mcase_frequency = {k.lower(): mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0) for k in mcase} print(mcase_frequency)
输出结果:
{‘a‘: 17, ‘b‘: 34, ‘z‘: 3}
3、集合生成式
3.1、求列表[1, -1, 2]中元素的平方值的集合
squared = {x**2 for x in [1, -1, 2]} print(squared)
输出结果:
{1, 4}
原文地址:https://www.cnblogs.com/bad-robot/p/9733573.html
时间: 2024-10-02 22:57:43