您当前的位置:首页 > IT编程 > python
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch |

自学教程:Python推导式数据处理方式

51自学网 2022-07-22 18:47:41
  python
这篇教程Python推导式数据处理方式写得很实用,希望能帮到您。

前言

推导式是一种独特的数据处理方式,可以快速的从一个数据序列构建另一个新的数据序列的结构体。常用的推导式有一下四种:

  • 列表推导式
  • 元组推导式
  • 集合推导式
  • 字典推导式

1、列表推导式

# coding:utf-8# Author:Yang Xiaopeng"""语法格式[表达式 for 变量 in 变量][表达式 for 变量 in 变量 if 条件表达式]上述格式中 的 表达式中的变量与for变量一致"""old_list = [1, 2, 3, 4, 5]new_list = [new_list * new_list for new_list in old_list] # yes [1, 4, 9, 16, 25]# new_list = [new_list1 * new_list for new_list in old_list] # NameError: name 'new_list1' is not defined# new_list = [new_list * new_list for new_list2 in old_list] # NameError: name 'new_list' is not definedold_list = [old_list * old_list for old_list in old_list] # yes [1, 4, 9, 16, 25]print(old_list)print(new_list)new_list = [old_list for old_list in old_list if old_list%2 == 1] # yes [1, 9, 25]print(new_list)

2、元组推导式

# coding:utf-8# Author:Yang Xiaopeng"""语法格式(表达式 for 变量 in 变量)(表达式 for 变量 in 变量 if 条件表达式)上述格式中 的 表达式中的变量与for变量一致"""old_list = (1, 2, 3, 4, 5)new_list = (new_list * new_list for new_list in old_list) # yes 1_4_9_16_25_# new_list = [new_list1 * new_list for new_list in old_list] # NameError: name 'new_list1' is not defined# new_list = [new_list * new_list for new_list2 in old_list] # NameError: name 'new_list' is not definedold_list = (old_list * old_list for old_list in old_list) # yes 1_4_9_16_25_for item in new_list:print(item, end="_")print("")for item in old_list:print(item, end="_")print("")

3、集合推导式

# coding:utf-8# Time:2022/6/28 20:57# Author:Yang Xiaopeng"""语法格式{表达式 for 变量 in 变量}{表达式 for 变量 in 变量 if 条件表达式}上述格式中 的 表达式中的变量与for变量一致"""old_list = {1, 2, 3, 4, 5}new_list = {new_list * new_list for new_list in old_list} # yes {1, 4, 9, 16, 25}# new_list = {new_list1 * new_list for new_list in old_list} # NameError: name 'new_list1' is not defined# new_list = {new_list * new_list for new_list2 in old_list} # NameError: name 'new_list' is not definedold_list = {old_list * old_list for old_list in old_list} # yes {1, 4, 9, 16, 25}print(old_list)print(new_list)new_list = {old_list for old_list in old_list if old_list % 2 == 1} # yes {1, 9, 25}print(new_list)

4、字典推导式

# coding:utf-8# Author:Yang Xiaopeng"""语法格式{key : value for key in 变量}{key : value for key in 变量 if 表达式}"""old_dict = ["Zhang", "Wang", "Yang", "Jim"]new_dict = {key:len(key) for key in old_dict} # yes {1, 4, 9, 16, 25}print(old_dict)print(new_dict)new_dict = {lll:len(lll) for lll in old_dict if len(lll) % 2 == 0} # yes {1, 9, 25}print(new_dict)

到此这篇关于Python推导式数据处理方式的文章就介绍到这了,更多相关Python推导式内容请搜索wanshiok.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持wanshiok.com!


使用Python去除小数点后面多余的0问题
python开发任意表达式求值全功能示例
51自学网,即我要自学网,自学EXCEL、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。
京ICP备13026421号-1