Python-Day6

常用数据类型练习题解答

一、元素分类

有如下值集合 [11,22,33,44,55,66,77,88,99],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}

l = [11, 22, 33, 44, 55, 66, 77, 88, 99]
d = {'k1': [], 'k2': []}
for i in l:
    if i >= 66:
        d['k1'].append(i)
    else:
        d['k2'].append(i)
print(d)

  

 

二、查找
查找列表中元素,移除每个元素的空格,并查找以 a或A开头 并且以 c 结尾的所有元素。
    li = ["alec", " aric", "Alex", "Tony", "rain"]
    tu = ("alec", " aric", "Alex", "Tony", "rain") 
    dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"}
li = ["alec", " aric", "Alex", "Tony", "rain"]
print(li)
for i in li[:]:
    x = li.index(i)
    li[x] = i.strip()
print(li)
l2 = []
for i in li[:]:
    if i.capitalize().startswith('A') and i.endswith('c'):
        l2.append(i)
print(l2)
#>>>>>>>>>>
['alec', ' aric', 'Alex', 'Tony', 'rain']
['alec', 'aric', 'Alex', 'Tony', 'rain']
['alec', 'aric']

tu = ("alec", " aric", "Alex", "Tony", "rain")
l3 = []
print(tu)
for i in tu:
    l3.append(i.strip())
tu = tuple(l3) #在循环里面逐个修改会报错:
print(tu)
l4 = []
for i in tu:
    if i.capitalize().startswith('A') and i.endswith('c'):
        l4.append(i)
tu4 = tuple(l4)
print(tu4)
#>>>>>>>>>>
('alec', ' aric', 'Alex', 'Tony', 'rain')
('alec', 'aric', 'Alex', 'Tony', 'rain')
('alec', 'aric')

dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"}
print(dic)
for i in dic.keys():
    dic[i] = dic[i].strip()
print(dic)
dic1 = {}
for i in dic.keys():
    if dic[i].capitalize().startswith('A') and dic[i].endswith('c'):
        dic1.update({i: dic[i]})
print(dic1)
#>>>>>>>>>>
{'k4': 'Tony', 'k2': ' aric', 'k1': 'alex', 'k3': 'Alex'}
{'k4': 'Tony', 'k2': 'aric', 'k1': 'alex', 'k3': 'Alex'}
{'k2': 'aric'}

  

三、输出商品列表,用户输入序号,显示用户选中的商品
    商品 li = ["手机", "电脑", '鼠标垫', '游艇']
li = ['手机', '电脑', '鼠标垫', '游艇']
print('Exit If Not Number!')
while True:
    s = input()
    if not s.isnumeric():
        print('Exit')
        break
    z = int(s)
    if z > 4 or z < 1:
        print('Input Again Please:')
        continue
    for k, i in enumerate(li, 1):
        if k == z:
            print(i)

  

四、购物车

功能要求:

  • 要求用户输入总资产,例如:2000
  • 显示商品列表,让用户根据序号选择商品,加入购物车
  • 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
  • 附加:可充值、某商品移除购物车
goods = [
    {"name": "电脑", "price": 1999},
    {"name": "鼠标", "price": 10},
    {"name": "游艇", "price": 20},
    {"name": "美女", "price": 998},
]

  

 

print('请输入您的总资产:')
assets = int(input())   #总资产
cart = []   #购物车
price = 0   #花销
balance = assets - price    #余额
goods = [
    {"name": "电脑", "price": 1999},
    {"name": "鼠标", "price": 10},
    {"name": "游艇", "price": 20},
    {"name": "美女", "price": 998},
]
print('序号', '物品', '\t', '价格')
for k, i in enumerate(goods, 1):
    print(k, '\t', i['name'], '\t', i['price'])
while True:
    menu = ['购买', '充值', '购物车']
    print('请输入操作序号:')
    for k, i in enumerate(menu, 1):
        print(k, i)
    print('********************************')
    choose = int(input())
    if choose == 1:
        while True:
            print('请输入要购买的商品序号,若要返回请按其他数字')
            seq = int(input())  # 购买物品的序号
            if seq > 4:
                break
            if balance - goods[seq - 1]['price'] < 0:
                print('余额不足!请前往充值!')
                break
            cart.append(goods[seq - 1])
            price += goods[seq - 1]['price']
            balance = assets - price
    elif choose == 2:
        print('请输入充值金额:')
        money = int(input())
        assets += money
        balance = assets - price
        print('充值成功!资产如下:')
        print('总资产:', assets, '\t' '总花费:', price, '\t', '余额:', balance)
    elif choose == 3:
        while True:
            print('********************************')
            print('Shopping Cart:')
            print('序号', '物品', '\t', '价格')
            for k, i in enumerate(cart, 1):
                print(k, '\t', i['name'], '\t', i['price'])
            print('总资产:', assets, '\t' '总花费:', price, '\t', '余额:', balance)
            print('********************************')
            menu_cart = ['移除', '结算']
            print('请输入操作序号,若要返回请按其他数字')
            for k, i in enumerate(menu_cart, 1):
                print(k, i)
            print('********************************')
            choose_cart = int(input())
            if choose_cart == 1:
                print('请输入要移除的商品在购物车的序号')
                rm = int(input())
                remove = cart.pop(rm - 1)
                price -= remove['price']
                balance += remove['price']
                print('移除成功!')
            elif choose_cart == 2:
                print('购买成功!订单如下')
                print('********************************')
                print('Shopping Cart:')
                print('序号', '物品', '\t', '价格')
                for k, i in enumerate(cart, 1):
                    print(k, '\t', i['name'], '\t', i['price'])
                print('总资产:', assets, '\t' '总花费:', price, '\t', '余额:', balance)
                print('********************************')
                exit()
            else:
                break

  突然发现,受C语言影响,这里将所有的输入输出分开写了。。。显得有些繁琐,在input()里面显示提示信息会好一些。

  另外,购物车结构可以优化,把相同的条目计数,如 {商品 ,单价,数目}

 

 五、用户交互,显示省市县三级联动的选择

dic = {
    "河北": {
        "石家庄": ["鹿泉", "藁城", "元氏"],
        "邯郸": ["永年", "涉县", "磁县"],
    },
    "河南": {
        "郑州": ["二七", "金水", "慧济"],
        "洛阳": ["龙门", "白马寺", "上清宫"],
    },
    "山西": {
        "太原": ["万柏林", "尖草坪", "杏花岭"],
        "临汾": ["尧都区", "金殿镇", "屯里镇"],
    }
}
sheng = input("输入省名查看市:")
for i in dic[sheng]:
    print(i)
shi = input("输入市名查看县区:")
for j in dic[sheng][shi]:
    print(j)

  

posted @ 2017-03-17 22:14  云中王  阅读(207)  评论(0编辑  收藏  举报