python推導式
初學python,可以評論互相交流,
# 串列推導式格式:
# 格式:[運算式 for 變數 in 舊串列] 不帶條件
# [運算式 for 變數 in 舊串列 if 條件] 帶條件
#將1-100之間能被3和5整除的數,組成一個新的串列
# newlist = [i for i in range(1,101) if i%3 == 0 and i%5 == 0]
# print(newlist)
# 利用0~5數字,在一個元組中前一個為偶數,后一個為奇數
#使用函式完成
# [(偶數,奇數),(),(),] [(0,1),(0,3),(0,5)...]
# def func():
# newlist = []
# for i in range(5):
# if i%2 == 0:
# for j in range(10):
# if j%2 != 0:
# newlist.append((i,j))
# return newlist
# x = func()
# print(x)
# 利用推導式完成
# newlist = [(x,y) for x in range(5) if x % 2 == 0 for y in range(10) if y % 2 != 0]
# print(newlist)
# 串列里有串列
# list1 = [[1,2,3],[4,5,6],[7,8,9],[1,3,5]]
# newlist = [i[2] for i in list1]
# print(newlist)
#含if和else的推導式
# if 薪資大于5000加200 else低于等于5000加500
# dict1 = {'name':'tom','salary':4900}
# dict2 = {'name':'lucy','salary':6000}
# dict3 = {'name':'jack','salary':8000}
# dict4 = {'name':'lily','salary':4000}
# list1 = [dict1,dict2,dict3,dict4]
# newlist = [employee['salary']+200 if employee['salary']>5000 else employee['salary']+500 for employee in list1]
# print(newlist)
# 集合推導式 {},類似串列推導式,多加了去除重復的功能
# list1 = [1,2,3,1,3,5,2,8,9,87,78]
# set1 = {x for x in list1 if x>5 }
# print(set1)
# 字典推導式 交換鍵和值的值
# dic1 = {'a':'A','b':'B','c':'C','d':'C'}
# newdict = {value:key for key,value in dic1.items()}
# print(newdict)
本文首發于python黑洞網,博客園同步跟新
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/273976.html
標籤:其他
