一、将列表中的字符串全部大写
# 方式一
names = ['albert', 'james', 'kobe', 'kd']
NAMES = [i.capitalize() for i in names]
print(NAMES)
# 方式二
print(list(map(lambda x: x.capitalize(), names)))
二、过滤
将其中以shenjing结尾的名字过滤掉,并保存剩下的名字的长度
# 方式一
names = ['albert', 'jr_shenjing', 'kobe', 'kd']
for i in range(3):
if names[i].endswith('shenjing') > 0:
names.pop(i)
names_len = [len(i) for i in names]
print(names)
print(names_len)
# 方式二
names_list = list(filter(lambda x: not x.endswith('shenjing'), names))
print(names_list)
print(list(map(lambda x: len(x), names_list)))
三、求文件中最长行的长度
# 方式一
maxnum = 0
with open('a.txt', mode='r', encoding='utf-8') as f:
for line in f:
if len(line.strip()) > maxnum:
maxnum = len(line.strip())
print(maxnum)
# 方式二
with open('a.txt', mode='r', encoding='utf-8') as f:
for line in f:
print(len(max([line.strip() for line in f], key=lambda x: len(x))))
四、对于文件shopping.txt
内容如下格式,分别代表商品,价格和数量
mac,20000,3
lenovo,3000,10
(1)求总共花了多少钱?
(2)打印出所有商品的信息,格式为[{‘name’:‘xxx’,'price:333,‘count’:3}, …]
(3)求单价高于10000的产品的信息,格式如上
# 1 total cost
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)
# 2 print all goods data
with open('shopping.txt', encoding='utf-8') as f:
info = [{
'name': line.strip().split(',')[0],
'price': float(line.strip().split(',')[1]),
'count': int(line.strip().split(',')[2]),
} for line in f]
print(info)
# 3 get the data price greater than 10000
with open('shopping.txt', encoding='utf-8') as f:
info = [{
'name': line.strip().split(',')[0],
'price': float(line.strip().split(',')[1]),
'count': int(line.strip().split(',')[2]),
} for line in f if float(line.strip().split(',')[1]) > 10000]
print(info)
合并
with open('shopping.txt') as f:
final_l, info_l, exp_l = [], [], []
for line in f:
line_list = line.split(',')
name = line_list[0]
price = int(line_list[1])
count = int(line_list[2])
final_l.append(price * count)
s = f"'name': '{name}', 'price': {price}, 'count': {count}"
info_l.append(eval('{' + s + '}'))
res = filter(lambda x: x['price'] > 10000, info_l)
exp_l.append(list(res))
print(sum(final_l))
print(info_l)
print(exp_l)