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推導式內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: