亲宝软件园·资讯

展开

Python推导式

匿名V5程序员​​​​​​​ 人气:0

前言

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

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)

加载全部内容

相关教程
猜你喜欢
用户评论