Python推导式详解:列表、元组、集合与字典的高效构建
本文详细介绍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 defined
old_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 defined
old_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 defined
old_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推导式相关内容,建议查阅本站过往文章或继续浏览后续教程,感谢支持!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









