Python列表推导式、字典推导式与集合推导式用法实例分析
作者:苍松 时间:2022-04-10 10:34:00
本文实例讲述了Python列表推导式、字典推导式与集合推导式用法。分享给大家供大家参考,具体如下:
推导式comprehensions(又称解析式),是Python的一种独有特性。推导式是可以从一个数据序列构建另一个新的数据序列的结构体。 共有三种推导,在Python2和3中都有支持:
列表(list)推导式
字典(dict)推导式
集合(set)推导式
一、列表推导式
1、使用[]生成list
基本格式
variable = [out_exp_res for out_exp in input_list if out_exp == 2]
out_exp_res:列表生成元素表达式,可以是有返回值的函数。
for out_exp in input_list:迭代input_list将out_exp传入out_exp_res表达式中。
if out_exp == 2:根据条件过滤哪些值可以。
例一:
multiples = [i for i in range(30) if i % 3 is 0]
print(multiples)
# Output: [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
例二:
def squared(x):
return x*x
multiples = [squared(i) for i in range(30) if i % 3 is 0]
print multiples
# Output: [0, 9, 36, 81, 144, 225, 324, 441, 576, 729]
2、使用()生成generator
将俩表推导式的[]改成()即可得到生成器。
multiples = (i for i in range(30) if i % 3 is 0)
print(type(multiples))
# Output: <type 'generator'>
二、字典推导式
字典推导和列表推导的使用方法是类似的,只不中括号该改成大括号。直接举例说明:
例子一:大小写key合并
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.keys()
if k.lower() in ['a','b']
}
print mcase_frequency
# Output: {'a': 17, 'b': 34}
例子二:快速更换key和value
mcase = {'a': 10, 'b': 34}
mcase_frequency = {v: k for k, v in mcase.items()}
print mcase_frequency
# Output: {10: 'a', 34: 'b'}
三、集合推导式
它们跟列表推导式也是类似的。 唯一的区别在于它使用大括号{}。
例一:
squared = {x**2 for x in [1, 1, 2]}
print(squared)
# Output: set([1, 4])
希望本文所述对大家Python程序设计有所帮助。
来源:https://www.cnblogs.com/tkqasn/p/5977653.html
标签:Python,列表推导式,字典推导式,集合推导式
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python爬取基于m3u8协议的ts文件并合并
2021-11-03 16:44:45
python实现多层感知器
2022-07-04 14:37:10
![](https://img.aspxhome.com/file/2023/8/91978_0s.jpg)
解决python gdal投影坐标系转换的问题
2021-11-02 12:14:55
Python Socket实现远程木马弹窗详解
2022-11-28 10:04:39
![](https://img.aspxhome.com/file/2023/2/101172_0s.png)
Python超细致探究面向对象
2023-05-28 17:02:56
Python 京东云无线宝消息推送功能
2021-08-19 09:45:57
Linux系统下使用XHProf和XHGui分析PHP运行性能
2023-11-14 23:56:33
![](https://img.aspxhome.com/file/2023/9/55769_0s.png)
Python3.9.1中使用match方法详解
2023-09-14 09:51:21
![](https://img.aspxhome.com/file/2023/9/60729_0s.png)
Flask之请求钩子的实现
2023-06-27 10:43:59
Python实现PS图像调整黑白效果示例
2022-08-06 09:15:13
![](https://img.aspxhome.com/file/2023/1/93781_0s.jpg)
用css+Javascript实现扫描线效果图片
2007-11-08 19:12:00
![](https://img.aspxhome.com/file/UploadPic/20072/200723113824691s.jpg)
Python学习笔记之lambda表达式用法详解
2022-01-28 15:39:37
为什么python比较流行
2023-06-26 02:24:22
基于python实现的百度新歌榜、热歌榜下载器(附代码)
2022-10-29 10:16:12
![](https://img.aspxhome.com/file/2023/9/100879_0s.png)
给Python初学者的一些编程技巧
2023-05-27 21:41:30
Golang 高效排序数据详情
2023-06-23 08:23:41
![](https://img.aspxhome.com/file/2023/6/87626_0s.jpg)
对python中不同模块(函数、类、变量)的调用详解
2022-01-17 14:36:38
python实现Scrapy爬取网易新闻
2021-11-23 17:02:11
![](https://img.aspxhome.com/file/2023/1/93691_0s.jpg)
交互设计实用指南系列(6) –标签明晰、有效
2010-01-21 12:39:00
![](https://img.aspxhome.com/file/UploadPic/20101/21/32-66s.jpg)
Python的Django框架中模板碎片缓存简介
2022-11-20 11:00:28