一、列表推导式: ls = [元素表达式 for i in 可迭代对象 if 筛选条件]
案例:
# -*- coding: utf-8 -*- '''列表生成式练习''' # 练习一(三元表达式):编写名为collatz(number)的函数;实现的功能:参数为偶数时,打印number// 2;参数为奇数时,打印3*number + 1 num = int(input('num:')) def collatz(number): pr_num = number // 2 if number % 2 == 0 else 3 * number + 1 print(pr_num) collatz(num) # 练习二:使用for循环,对列表元素的类型进行更改 ls = [1, 2, 3, 4, 5, 6, 7, 9] ls1 = [str(i) for i in ls if i % 2 == 0] print(ls1) # ['2', '4', '6'] ls = [str(i) for i in ls] print(ls) # ['1', '2', '3', '4', '5', '6', '7', '9'] # 练习三: 找出1-10之间的所有偶数,并且返回一个列表(包含以这个偶数为半径的圆的面积) ls = [i ** 2 * 3.14 for i in range(1, 11) if i % 2 == 0] print(ls) # [12.56, 50.24, 113.04, 200.96, 314.0] import math li = [math.pi * r * r for r in range(2, 11, 2)] print(li) # 找出1-10之间的所有奇数,并且返回一个列表(转换奇数为字符串) ls = [str(i) for i in range(1, 11) if i % 2 == 1] print(ls) # ['1', '3', '5', '7', '9'] # 练习四:找出1-50之间的所有质数 def isPrime(num): for i in range(2, num): if num % i == 0: return False return True ls2 = [i for i in range(1, 50) if isPrime(i)] print(ls2) # [3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49]
二、生成器推导式:creater = (元素表达式 for i in 可迭代对象 if 筛选条件)
案例:
"""生成器表达式""" # 生成器表达式就是把列表中的[]换成()就形成了生成器表达式 # 示例:母鸡生一筐鸡蛋编程了,给你个母鸡,需要下蛋的时候就下蛋 chicken = ('鸡蛋%s' % i for i in range(5)) print(chicken) # <generator object <genexpr> at 0x00000000027ED620> 得到的是生成器对象 print(next(chicken)) # 鸡蛋0 print(list(chicken)) # ['鸡蛋1', '鸡蛋2', '鸡蛋3', '鸡蛋4']
三、字典推导式 :dic = {k:v for k,v in 可迭代对象 if 筛选条件}
案例:
'''(二)字典生成式''' # # 练习一: 假设有num1个学生,成绩在60-100之间,筛选出成绩在90分以上的学生 def filter_score(num1): count = 0 dic_ns = {} while count < num1: name = input('name:') score = int(input('score')) count += 1 dic_ns[name] = score dic = {k: v for k, v in dic_ns.items() if v >= 90} print(dic) # filter_score(5) # 练习二: 将字典中的key值和value值调换 dic1 = {'q': 1, 'z': 2, 'k': 3} def change(dic): dic = {v: k for k, v in dic.items()} print(dic) change(dic1) # {1: 'q', 2: 'z', 3: 'k'} # 练习三:大小写合并,Key值最终全部为小写 dic2 = {'q': 'QQWSAS', 'Z': 'ASDqq', 'k': 'qqAA'} def lower_my(dic): dic = {k: v.lower() for k, v in dic.items()} print(dic) lower_my(dic2) # {'q': 'qqwsas', 'Z': 'asdqq', 'k': 'qqaa'}
四、三元表达式: res = 值1 if 条件 else 值2 # 条件成立时返回值1,条件不成立时返回值2
案例:
"""三元表达式""" def fn(a, b): if a > b: return a return b print(fn(3, 8)) # 8 def fn(a, b): return a if a > b else b print(fn(5, 3)) # 5 # 将三元表达式用于列表生成式中 a = [1, 2, 3, 4, 5, 6, 7, 8, 9] b = [i if i > 3 else i + 1 for i in a if i < 7] print(b) # [2, 3, 4, 4, 5, 6]
转载于:https://www.cnblogs.com/qianzhengkai/p/10679439.html