python学习之路——作业 day16(18/10/10)

# 1、将names=['egon','alex_sb','wupeiqi','yuanhao']中的名字全部变大写
names=['egon','alex_sb','wupeiqi','yuanhao']
name = [name.upper() for name in names]
print(name)


# 2、将names=['egon','alex_sb','wupeiqi','yuanhao']中以sb结尾的名字过滤掉,然后保存剩下的名字长度
names=['egon','alex_sb','wupeiqi','yuanhao']
name = [len(name) for name in names if not name.endswith('sb')]
print(name)

# 3、求文件a.txt中最长的行的长度(长度按字符个数算,需要使用max函数)
with open('a.txt','rt',encoding='utf-8') as f:
print(max(len(line) for line in f))


# 4、求文件a.txt中总共包含的字符个数?思考为何在第一次之后的n次sum求和得到的结果为0?(需要使用sum函数)
with open('a.txt','rt',encoding='utf-8') as f:
print(sum(len(line) for line in f))


# 5、思考题
# with open('a.txt') as f:
# g=(len(line) for line in f)
# print(sum(g)) #为何报错?
  因为文件在print之前已经关闭了,调用g需要文件是开着的


# 6、文件shopping.txt内容如下
# mac,20000,3
# lenovo,3000,10
# tesla,1000000,10
# chicken,200,1
# 求总共花了多少钱?
with open('shopping.txt',encoding='utf-8') as f:
info=[line.strip().split(',') for line in f]
cost=sum(float(unit_price)*int(count) for _,unit_price,count in info)
print(cost)


# 打印出所有商品的信息,格式为[{'name':'xxx','price':333,'count':3},...]
with open('shopping.txt','rt',encoding='utf-8') as f:
goods_info = [{
'name': line.strip().split(',')[0],
'price': float(line.strip().split(',')[1]),
'count': int(line.strip().split(',')[2]),
}for line in f]
print(goods_info)


# 求单价大于10000的商品信息,格式同上
with open('shopping.txt','rt',encoding='utf-8') as f:
info=[line.strip().split(',') for line in f]
# print(info)
msg = filter(lambda x:float(x[1])>10000,info)
msg1 = map(lambda x:{'name':x[0],'price':x[1],'count':x[2]},msg)
li= [i for i in msg1]
print(li)


# 想从一个按照从小到大排列的数字列表中找到指定的数字,遍历的效率太低,用二分法(算法的一种,算法是解决问题的方法)可以极大低缩小问题规模
li=[1,2,10,30,33,99,101,200,301,311,402,403,500,900,1000]
def search(x,li):
print(li)
if len(li) == 0:
print('没有')
return
mid_li = len(li) // 2
if x > li[mid_li]:
li = li[mid_li+1:]
search(x,li)
elif x < li[mid_li]:
li = li[:mid_li]
search(x,li)
else:
print('找到')
return

search(10,li)

猜你喜欢

转载自www.cnblogs.com/unbrokenlin/p/9767447.html
今日推荐