Python课程设计 第 17 / 52 篇

合并表达-参考答案

作业1

将names=[‘albert’,‘james’,‘kobe’,‘kd’]中的名字全部变大写

# 方式一
names = ['albert', 'james', 'kobe', 'kd']
NAMES = [i.capitalize() for i in names]
print(names)
print(NAMES)

# 方式二
print(list(map(lambda x: x.capitalize(), names)))

作业2

将names=[‘albert’,‘jr_shenjing’,‘kobe’,‘kd’]中以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)))

作业3

求文件a.txt中最长的行的长度(长度按字符个数算,需要使用max函数)

# 方式一
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))))

作业4

文件shopping.txt内容如下,分别代表商品,价格和数量

mac,20000,3

lenovo,3000,10

bmw,1000000,10

chicken,200,1

(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)