奇趣5分彩

Python推导式数据处置体例

 更新时候:2022年07月12日 11:42:08   作者:匿名V5法式员​​​​​​​  
这篇文章首要先容了Python推导式数据处置体例,文章环绕主题睁开具体的内容先容,具备必然的参考代价,须要的伴侣能够参考一下

媒介

推导式是一种怪异的数据处置体例,能够疾速的从一个数据序列构建另外一个新的数据序列的布局体。经奇趣5分彩操纵的推导式奇趣5分彩一下四种:

  • 列表推导式
  • 元奇趣5分彩推导式
  • 调集推导式
  • 字典推导式

1、列表推导式

# coding:utf-8
# Author:Yang Xiaopeng

"""
语法格局
[抒发式 for 变量 in 变量]
[抒发式 for 变量 in 变量 if 前提抒发式]
上述格局奇趣5分彩 的 抒发式奇趣5分彩的变量与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、元奇趣5分彩推导式

# coding:utf-8
# Author:Yang Xiaopeng

"""
语法格局
(抒发式 for 变量 in 变量)
(抒发式 for 变量 in 变量 if 前提抒发式)
上述格局奇趣5分彩 的 抒发式奇趣5分彩的变量与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 前提抒发式}
上述格局奇趣5分彩 的 抒发式奇趣5分彩的变量与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推导式内容请搜刮剧本之奇趣5分彩之前的文章或持续阅读上面的相干文章但愿大师今后多多撑持剧本之奇趣5分彩!

相干文章

最新批评