python通用编程二阶段:匿名函数

一、将列表中的字符串全部大写

# 方式一
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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值