python列表推导式练习总结:
问题一
如何快速生成一个列表
[“data0”,“data1”,“data2”,“data3”,…,“data99”,]
问题二
如何快速生成一个列表[“data0”,“gy1”,“data2”,“gy3”,…,“data98”,“gy99”]
列表以下方法总结如代码:
""" 需求一:如何快速生成一个["data0","data1","data2","data3",...,"data99",] """ # 简单 li = [] for i in range(100): li.append("data{}".format(i)) print(li) # 列表推导式 li2 = ['data{}'.format(i) for i in range(100)] print(li2) """ 把上述列表中data后面为偶数的数据过滤掉, 即,只要奇数的 """ # 方法一、打印奇数,可以通过修改步长 li3 = ["data{}".format(i) for i in range(1,100,2)] print(li3) # 推导式结合if条件句 li4 =['data{}'.format(i) for i in range(1,100) if i % 2 == 1] print(li4) """ 需求二:如何快速生成一个["data0","gy1","data2","gy3",...,"data98","gy99"] """ # 常规写法 li = [] for i in range(100): if i % 2 == 0: li.append("data{}".format(i)) else: li.append("gy{}".format(i)) print(li) # 三元运算符 # n = int(input("请输入一个数字")) # number = "大于10" if 10 < n else "小于10" # print(number) # 推导式结合三元运算符的使用 res = ["data{}".format(i) if i%2==0 else "gy{}".format(i) for i in range(100)] print(res)
字典推导式:
""" 语法 1.字典推导式基本语法 dic = {k:v for x in xxx} 2.字典推导式结合 if进行过滤 dic = {k:v for x in xxx if xx} 3.字典推导式结合 三元运算符使用 dic = {k:v if xx else k1:v1 for x in xxx} """ # 需求:有一个列表li,把他转换为一个元素下表为键,值为元素的字典格式的数据 # 常规语法 li = ['a','b','c','d','e','f','g','h'] dic = {} for i, j in enumerate(li): dic[i] = j print(dic) # 字典推导式 dic1 = {i:j for i, j in enumerate(li)} print(dic ) # 例题 cookie='sensorsdata2015js=distinctd217c1c1e7d261204ice_i; ' 'Token=07b608b2b6b54ec6aa4c95bd7f5cc1d48842f; ' 'Userid=021003a060271958.882586769905111041; ' 'TGC=U' # res = cookie.split(';') # dic2 = {} # # strip去除空格 # for i in res: # d = i.split('=') # key = d[0].strip() # value = d[1].strip() # dic2[key] = value # print(dic2) dic3 = {item.split('=')[0] : item.split('=')[1] for item in cookie.split(';')} print(dic3) # 双重for循环 dic4 = {k : v for item in cookie.split(';') for k,v in [item.split('=')]} print(dic4)
集合推导式和生成器表达式
""" 列表推导式 : [x for x in xxx] 字典推导式 : {k:v for x in xxx} 集合推导式 : {x for x in xxx} 生成器推导式 : (x for x in xxx) """ # 集合推导式 se = {i for i in range(10)} print(se) # 生成器表达式--->返回的是一个生成器对象(不是元祖) gen = (i for i in range(10)) print(gen)
练习
1. 生成包含1到100之间的10个随机数的列表
# 方法一 常规方法 liss = [] for i in range(10): s = random.randint(1,100) liss.append(s) print(liss) # 方法二 列表推导式 lir = [ random.randint(1,100) for i in range(10)] print(liss)
2. 有四个数字:1、2、3、4能组成多少个互不相同且无重复数字的三位数?各是多少?
# 方法一 常规方法 lis1 = [1,2,3,4] for i in lis1: for j in lis1: for k in lis1: if i != j and j !=k and k != i: print(i,j,k) # 方法二 列表推导式 lis = [x * 100 + y * 10 + z for x in range(1, 5) for y in range(1, 5) for z in range(1, 5) if x != y and x != z and y != z] print(lis)
3. 通过字典推导式,颠倒字典的键名和值:将{‘py’: “python09”, ‘java’: “java09”}
转换为: {‘python09’: “py”, ‘java09’: “java”}
dic = {'py': "python09", 'java': "java09"} dic1 = {v:k for k,v in dic.items() } print(dic1)
4. 将字典{‘x’: ‘A’, ‘y’: ‘B’, ‘z’: ‘C’ }
通过推导式转换为:[‘x=A’,‘y=B’,‘z=C’]
dic2 = {'x': 'A', 'y': 'B', 'z': 'C' } li1 = ['{}={}'.format(k,v) for k,v in dic2.items()] li2 = [f'{k}={v}' for k,v in dic2.items()]
5. Names=[‘python’,‘java’,‘php’,‘c’,‘c++’,‘django’,‘unittest’,‘pytest’,‘pymysql’]
,请通过列表推导式,获取names中字符串长度大于4的元素
Names=['python','java','php','c','c++','django','unittest','pytest','pymysql'] new_name = [] for i in Names: if len(i) > 4: new_name.append(i) print(new_name) # 方法二 列表推导式 names = [i for i in Names if len(i)>4] print(names)
6. 通过列表推导式完成下面数据类型转换。
将 ["{‘a’:11,‘b’:2}", “[11,22,33,44]”] 转换为以下格式: li1 = [{‘a’: 11, ‘b’: 2}, [11, 22, 33, 44]]
# 考察列表推导式 li = ["{'a':11,'b':2}", "[11,22,33,44]"] # 方法一 new_list = [] for i in li: res=eval(i) new_list.append(res) print(new_list) # 方法二 列表推导式 res = [ eval(i) for i in li ] print(res)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)