Python-Day6

經常使用數據類型練習題解答

1、元素分類python

有以下值集合 [11,22,33,44,55,66,77,88,99],將全部大於 66 的值保存至字典的第一個key中,將小於 66 的值保存至第二個key的值中。
即: {'k1': 大於66的全部值, 'k2': 小於66的全部值}api

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)

  

 

2、查找
查找列表中元素,移除每一個元素的空格,並查找以 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'}

  

3、輸出商品列表,用戶輸入序號,顯示用戶選中的商品
    商品 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)

  

4、購物車

功能要求:app

  • 要求用戶輸入總資產,例如: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()裏面顯示提示信息會好一些。優化

  另外,購物車結構能夠優化,把相同的條目計數,如 {商品 ,單價,數目}spa

 

 5、用戶交互,顯示省市縣三級聯動的選擇blog

dic = {
    "河北": {
        "石家莊": ["鹿泉", "藁城", "元氏"],
        "邯鄲": ["永年", "涉縣", "磁縣"],
    },
    "河南": {
        "鄭州": ["二七", "金水", "慧濟"],
        "洛陽": ["龍門", "白馬寺", "上清宮"],
    },
    "山西": {
        "太原": ["萬柏林", "尖草坪", "杏花嶺"],
        "臨汾": ["堯都區", "金殿鎮", "屯裏鎮"],
    }
}
sheng = input("輸入省名查看市:")
for i in dic[sheng]:
    print(i)
shi = input("輸入市名查看縣區:")
for j in dic[sheng][shi]:
    print(j)
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息