【凤凰社】python推导式

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黑洞网,博客园同步跟新

 

 
 

0 评论

回复