作业12
一、实现将列表内的值全部变为大写
names=['egon','alex_sb','wupeiqi','yuanhao'] new_name = [line.upper() for line in names] print(new_name)
二、将列表内的结尾带有sb的值全部过滤,保留其余列表内值的长度
names=['egon','alex_sb','wupeiqi','yuanhao'] new_name = [] for line in names: if not line.endswith('sb'): new_name.append(line) print(new_name) new_name = [line for line in names if not line.endswith('sb')] print(new_name)
三、求文件中最长行的长度,需使用max函数
with open('test.txt') as f1: print(max(len(line) for line in f1))
四、求文件内一共包含的字符个数,并思考为何在第一次之后的n次sum求和得到的结果为0
with open('test.txt') as f1: print(sum(len(line) for line in f1)) print(sum(len(line) for line in f1)) 【res = 0# 文件未关闭基于上一次的读取文件指针是在文件末尾】
五、思考为何报错
with open('a.txt') as f: g=(len(line) for line in f) print(sum(g))
g目前是一个迭代器对象不可以计算总和
六、
1.求购物车文件内的总价
2.打印所有商品信息,格式为字典形式
3.求所以单价大于10000的商品,格式同上
shop_car = []
with open('test.txt',mode='rt',encoding='utf-8') as f1:
for line in f1:
res = line.strip('\n').split(',')
data = {'name':res[0],'price':int(res[1]),'count':int(res[2])}
shop_car.append(data)
print(shop_car)
print(sum(line['price'] * line['count'] for line in shop_car))
new_shop = [line for line in shop_car if line['price'] > 10000]
print(new_shop)
七、实现判断用户输入的数字是否存在于列表(不使用 in)
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9] def beanry_search(find_num,nums): print(nums) if len(nums) == 0: print('no here') return mid_index = len(nums) // 2 if find_num > nums[mid_index]: nums = nums[mid_index+1:] beanry_search(find_num,nums) elif find_num < nums[mid_index]: nums = nums[:mid_index] beanry_search(find_num,nums) else: print('is here!') beanry_search(3,nums)
八、实现将用户输入的数字的索引值取出(不使用 index)
l = [1,5,67,78,123,456,467,678,1000] def beanry_cearch(num,l,star=0,stop = len(l) -1): if star <= stop: middle = star+(stop - star) // 2 print('start:[%s] stop:[%s] middle:[%s] mid_val:[%s]'%(star,stop,middle,l[middle])) if num > l[middle]: star = middle+1 elif num < l[middle]: stop = middle-1 else: print('find it',middle) return beanry_cearch(num,l,star,stop) else: print('no exits') return beanry_cearch(456,l)