列表推导式

# 旧的列表-----》新的列表
# 1.列表推导式:格式:[表达式for变量in 旧列表] 或者[[表达式for变量in 旧列表 if 条件]
# 过滤掉长度小于等于3的人名
# names = ['tom', 'jack', 'jason', 'cc', 'bob', 'nick']
# result = [name for name in names if len(name) > 3]
# print(result)
#
# # 首字母大写
# names = ['tom', 'jack', 'jason', 'cc', 'bob', 'nick']
# result = [name.capitalize() for name in names if len(name) > 3]
# print(result)

# 将1~100之间能被3整除的,组成一个新的列表
# list1 = [i for i in range(1, 101) if i<101]
# print(list1)
# list_new =[i for i in list1 if i%3 ==0]
# print(list_new)
# 下面的写法一步到位
# list1 = [i for i in range(1, 101) if i%3 == 0]

# list1 = [(i, j) for i in range(5) for j in range(10) if i % 2 ==0 and j % 2 != 0]
# print(list1)

# list1 = [[1, 2, 3], [2, 4, 5], [7, 8, 9], [2, 5, 9]] ------------->[3,6,9,9]
# list1 = [[1, 2, 3], [2, 4, 5], [7, 8, 9], [2, 5, 9]]
# list2 = [i[-1] for i in list1]
# print(list2)

# dict1 = {'name': 'jack1', 'salary': 5000}
# dict2 = {'name': 'jack2', 'salary': 6000}
# dict3 = {'name': 'jack3', 'salary': 7000}
# dict4 = {'name': 'jack4', 'salary': 8000}
# list1 = [dict1, dict2, dict3, dict4]
# list2 = [employee['salary'] + 200 if employee['salary'] > 5000 else employee['salary'] +500 for name,employee in list1]
# print(list1)
# print(list2)

#集合推导式 和列表推导式是一样的 只是加上了一个去重复的功能


# list1 = [1,2,5,1,23,5,12,3,0]
# set1 = {x+1 for x in list1}
# print(set1)
#
# #字典推导式
# dict1 = {'name':'zzh','qq':862700720}
# set2 = {value:key for key,value in dict1.items()}
# print(set2)
# 返回的结果一定要如何key是唯一的这一条属性
posted @ 2020-02-14 13:01  smartcat994  阅读(142)  评论(0编辑  收藏  举报