py列表练习

第一关

1. 创建购物车列表shopping_list,列表中包含元素“牛奶”、“可乐”、“牛肉罐头”、“橘子”和“白菜”。

2. 顾客突然主意,不想买“牛肉罐头”,而是想换成“金枪鱼罐头”时,请更改列表中的元素。

3. 输出原列表与变更后的列表。请在下面输入你的代码。

shopping_list = ['牛奶','可乐','牛肉罐头','橘子','白菜']
print(shopping_list)
shopping_list[2] = '金枪鱼罐头'
print(shopping_list)

第二关

1. 先向列表中添加元素”鸡蛋“和”鸡胸肉“,输出新列表。

2. 再从列表中删除元素”可乐“和”金枪鱼罐头“,输出新列表。

shopping_list.append('鸡蛋')
shopping_list.append('鸡胸肉')
print(shopping_list)
shopping_list.remove('可乐')
shopping_list.remove('金枪鱼罐头')
print(shopping_list)

第三关

1. 将列表price_list中元素按照从大到小排列,输出新列表sorted_prices。

2. 将列表sorted_prices中元素逆序排列,输出新列表reversed_prices。

sorted_prices = sorted(price_list,reverse = True)
print(sorted_prices)
reversed_prices = reversed(sorted_prices)
print(list(reversed_prices))

第四关

1. 将购物车列表shopping_cart中的后5个元素放入到新列表list_new中,并打印出来

2. 将新列表list_new中的元素前两个元素替换成“苹果“和”沙拉酱“,然后打印出来。

list_new = []
list_new = shopping_cart[3:]
print(list_new)
list_new[0] = '苹果'
list_new[1] = '沙拉酱'
print(list_new)

评论

暂无评论