python学习日记(内置、匿名函数练习题)
用map来处理字符串列表
用map来处理字符串列表,把列表中所有水果都变成juice,比方apple_juice
fruits=['apple','orange','mango','watermelon']
fruits=['apple','orange','mango','watermelon'] def func(fruit): return fruit+'_juice' f = map(func,fruits) print(list(f))
匿名函数实现:
fruits=['apple','orange','mango','watermelon'] print(list(map(lambda fruit:fruit+'_juice',fruits)))
用filter函数处理数字列表
用filter函数处理数字列表,将列表中所有的偶数筛选出来
num = [1,3,5,6,7,8]
num = [1,3,5,6,7,8] def func(x): return x%2 == 0 l = filter(func,num) print(list(l))
匿名函数实现:
num = [1,3,5,6,7,8] print(list(filter(lambda x:x%2 == 0,num))) # print(list(filter(lambda x:True if x%2 == 0 else False,num)))
随意写一个20行以上的文件...
如题
随意写一个20行以上的文件
运行程序,先将内容读到内存中,用列表存储;
接收用户输入页码,每页5条,仅输出当页的内容。
简单实现:
with open('file',encoding='utf-8') as f: line = f.readlines() pages,left = divmod(len(line),5)#pages-->拥有五行的总页数,left-->余下一页的行数 page_num = int(input('请输入页码(整数):')) if page_num <= 0 or page_num > pages+1: print('页码不存在') elif page_num > 0 and page_num <= pages: for i in range(5): print(line[(page_num-1)*5+i].strip()) else: for i in range(left): print(line[(page_num - 1) * 5 + i].strip())
升级版(交互式)
with open('file',encoding='utf-8') as f: line = f.readlines() pages,left = divmod(len(line),5)#pages-->拥有五行的总页数,left-->余下一页的行数 while True: page_num = input('请输入页码(Q退出case-insensitive):') if page_num.lower() == 'q': print('阅读结束') break else: if page_num.isdigit(): page_num = int(page_num) if page_num <= 0 or page_num > pages + 1: print('页码不存在') print('请重新输入') continue elif page_num > 0 and page_num <= pages: for i in range(5): print(line[(page_num-1)*5+i].strip()) continue else: for i in range(left): print(line[(page_num - 1) * 5 + i].strip()) continue else: print('请输入整数') continue
如下,每个小字典的name对应股票名字...
如题
如下,每个小字典的name对应股票名字,shares对应多少股,price对应股票的价格
#如下,每个小字典的name对应股票名字,shares对应多少股,price对应股票的价格 portfolio = [ {'name': 'IBM', 'shares': 100, 'price': 91.1}, {'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}, {'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'ACME', 'shares': 75, 'price': 115.65}] # 1.计算购买每支股票的总价 # 2.用filter过滤出,单价大于100的股票有哪些
1.计算购买每支股票的总价
def func(dic): return {dic['name']:dic['shares']*dic['price']} r = map(func,portfolio) print(list(r))
匿名函数改进
print(list(map(lambda dic:{dic['name']:round(dic['shares']*dic['price'],2)},portfolio)))
2.用filter过滤出,单价大于100的股票有哪些
def func(dic): return dic['price'] > 100 r = filter(func,portfolio) print(list(r))
匿名函数实现
print(list(filter(lambda dic:dic['price'] > 100,portfolio)))
pass
作者:Gruffalo
---------------------------------------------
天行健,君子以自强不息
地势坤,君子以厚德载物
内容仅为自己做日常记录,备忘笔记等
真小白,努力学习ing...一起加油吧!(ง •̀_•́)ง