Python 簡化for循環:列表,集合與字典生成式


列表生成式

# 使用列表生成選擇特定的行
my_data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
rows_to_keep = [row for row in my_data if row[2] > 5]
print("Output #1 (list comprehension): {}".format(rows_to_keep))

列表生成式的意義是:對於my_data中的每一行,如果這行中索引位置2的值大於5,則保留這行。

集合生成式

#使用集合生成式在列表中選擇出一組唯一的元組
my_data = [(1, 2, 3), (4, 5 ,6), (7, 8, 9), (7, 8, 9)]
set_of_tuples1 = {x for x in my_data}
print("Output #2 (set comprehension): {}".format(set_of_tuples1))
set_of_tuples2 = set(my_data)                  #內置的set函數更好
print("Output #3 (set function): {}".format(set_of_tuples2))

字典生成式

#使用字典生成式選擇特定的鍵-值對
my_dictionary = {'customer1': 7, 'customer2': 9, 'customer3': 11}
my_results = {key : value for key, value in my_dictionary.items() if value > 10}
print("Output #3 (dictionary comprehension): {}".format(my_results))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM