p.MsoNormal { margin: 0pt; margin-bottom: .0001pt; text-align: justify; font-family: Calibri; font-size: 10.5000pt }
p.pre { margin: 0pt; margin-bottom: .0001pt; text-align: left; font-family: 宋体; font-size: 12.0000pt }
span.msoIns { text-decoration: underline; color: blue }
span.msoDel { text-decoration: line-through; color: red }
div.Section0 { }
一、元素分类
有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {‘k1‘: 大于66的所有值, ‘k2‘: 小于66的所有值}
li1 = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]
dic1 = {‘high66‘: [], ‘low66‘: []}
for i1 in li1:
if i1 > 66:
dic1[‘high66‘].append(i1)
elif i1 < 66:
dic1[‘low66‘].append(i1)
print(dic1)
二、查找
查找列表中元素,移除每个元素的空格,并查找以 a或A开头 并且以 c 结尾的所有元素。
li = ["alec", " aric", "Alex", "Tony", "rain"]
tu = ("alec", " aric", "Alex", "Tony", "rain")
dic = {‘k1‘: "alex", ‘k2‘: ‘ aric‘, "k3": "Alex", "k4": "Tony"}
dic2 = {‘k1‘: ‘alec‘, ‘k2‘: ‘Aric‘, ‘k3‘: ‘Alex‘, ‘k4‘: ‘Tony‘}
for dic2_1 in dic2:
if (dic2[dic2_1].startswith(‘a‘) or dic2[dic2_1].startswith(‘A‘)) and dic2[dic2_1].endswith(‘c‘):
print(dic2_1, dic2[dic2_1])
三、输出商品列表,用户输入序号,显示用户选中的商品
商品 li = ["手机", "电脑", ‘鼠标垫‘, ‘游艇‘]
li3 = [‘手机‘, ‘电脑‘, ‘鼠标垫‘, ‘游艇‘]
for li3_1 in enumerate(li3):
print(li3_1)
choice3_inp = input(‘请输入你要选择的商品序号(0-3):‘)
choice3_inp = int(choice3_inp)
print(li3[choice3_inp])
四、购物车
功能要求:
要求用户输入总资产,例如:2000
显示商品列表,让用户根据序号选择商品,加入购物车
购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
附加:可充值、某商品移除购物车
goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
]
goods = [ # 购物车以商品清单为基础,增加一个表示商品数量的键值对
{"name": "电脑", "price": 1999, "num": 0},
{"name": "鼠标", "price": 10, "num": 0},
{"name": "游艇", "price": 20, "num": 0},
{"name": "美女", "price": 998, "num": 0},
]
wallet = 0
tag4 = True
while tag4:
choice4_inp = input(‘你的余额是%s元,请选择:1、充值 2、购物 3、结算 ‘ % (wallet))
if choice4_inp == ‘1‘: # 第一个选项是充值
charge_inp = int(input(‘请输入充值的金额:‘))
wallet = wallet + charge_inp
print(‘充值成功‘)
elif choice4_inp == ‘2‘: # 第二个选项是商品购买
while True:
for li4_1 in enumerate(goods, 1):
print(li4_1)
buy_inp = input(‘请输入你要购买的商品(输入q返回,输入c修改购物车):‘)
if buy_inp == ‘q‘:
break
elif buy_inp == ‘c‘: # 清空购物车
while True:
for shopping_car_1 in enumerate(goods, 1):
print(shopping_car_1)
car_inp = input(‘清空商品请输入对应序号(输入q返回上一菜单):‘)
if car_inp == ‘q‘:
break
car_inp = int(car_inp) - 1
goods[car_inp][‘num‘] = 0
elif buy_inp.isdigit(): # ,购买成功,对应商品的num加一
buy_inp = int(buy_inp) - 1
goods[buy_inp][‘num‘] += 1
print(‘商品加入购物车!‘)
else:
print(‘输入错误,请重新输入‘)
elif choice4_inp == ‘3‘: # 第三个选项是结算,余额>=账单则购买成功
bill = 0
for pay in range(0, len(goods)):
bill = bill + goods[pay][‘price‘] * goods[pay][‘num‘]
wallet = wallet - bill
if wallet >= 0:
print(‘购物完成,你消费了共%s元,余额%s元‘ % (bill, wallet))
print(‘**购物清单**‘)
for ending in goods:
if ending[‘num‘] > 0:
print(ending[‘name‘], ending[‘num‘])
else:
print(‘穷逼,88!‘)
tag4 = False