声明式编程题

声明式编程练习题:

1、将names=['egon','alex_sb','wupeiqi','yuanhao']中的名字全部变大写
names = ['egon', 'alex_sb', 'wupeiqi', 'yuanhao'] # 方式一:手动实现 new_names = [] for line in names: new_names.append(line.swapcase()) print(new_names) # 方式二:列表生成式 new_names = [line.swapcase() for line in names] print(new_names) # 方式三:map+匿名函数 res = map(lambda line: line.swapcase(), names) print(list(res)) names = [name.upper() for name in names] print(names)

2、将names=['egon','alex_sb','wupeiqi','yuanhao']中以sb结尾的名字过滤掉,然后保存剩下的名字长度
names = ['egon', 'alex_sb', 'wupeiqi', 'yuanhao'] new_names = [] for line in names: if not line.endswith('sb'): new_names.append(line) print(new_names) new_names = [len(line) for line in names if not line.endswith('sb')] print(new_names) res = filter(lambda line: not line.endswith('sb'), names) print(list(res)) 3、求文件a.txt中最长的行的长度(长度按字符个数算,需要使用max函数)
file = [] with open('a.txt', 'rt', encoding='utf-8')as f: for line in f: res = f.read() # print(res) res = res.split('\n') file.append(res) print(file) def funcs(x): return len(x) res = max(file, key=funcs) print(res) res2 = max(res, key=funcs) print(len(res2)) 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)) print(sum(len(line) for line in f)) # 求包换换行符在内的文件所有的字符数,为何得到的值为0? 5、思考题
with open('a.txt') as f: g = (len(line) for line in f) print(sum(g)) # 为何报错? with open('a.txt') as f: print(sum(len(line) for line in f)) print(sum(g)) # 为何报错?(len(line) for line in f)时循环多个值 6、文件shopping.txt内容如下
mac,20000,3 lenovo,3000,10 tesla,1000000,10 chicken,200,1 求总共花了多少钱? 打印出所有商品的信息,格式为[{'name':'xxx','price':333,'count':3},...] 求单价大于10000的商品信息,格式同上 with open('shopping.txt', 'rt', encoding='utf-8') as f: info = [line.strip('\n').split(',') for line in f] print(info) cost = sum(float(unit_price) * int(count) for _, unit_price, count in info) print(cost) with open('shopping.txt', 'rt', encoding='utf-8') as f: # for line in f: # print(line) info = [{'name': line.strip('\n').split(',')[0], 'price': int(line.strip('\n').split(',')[1]), 'count': int(line.strip('\n').split(',')[2])} for line in f] print(info) with open('shopping.txt', encoding='utf-8') as f: info = [{'name': line.strip('\n').split(',')[0], 'price': int(line.strip('\n').split(',')[1]), 'count': int(line.strip('\n').split(',')[2])} for line in f if int(line.strip('\n').split(',')[1]) > 10000] print(info)

 

posted @ 2018-10-12 19:35  ChuckXue  阅读(183)  评论(0编辑  收藏  举报