1. 程式人生 > >python基本數據類型練習

python基本數據類型練習

num 價格 安慶 bubuko 需要 price 結算 mage pri

一、元素分類
# 有如下值集合 [11,22,33,44,55,66,77,88,99,90...],將所有大於 66 的值保存至字典的第一個key中,將小於 66 的值保存至第二個key的值中。
# 即: {‘k1‘: 大於66的所有值, ‘k2‘: 小於66的所有值}

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

二、查找
1、 查找列表中元素,移除每個元素的空格,並查找以 a或A開頭 並且以 c 結尾的所有元素

li = ["alc", " aric ", "Aex", "Tny", "rain"]
list1 =[]
for l in li:
    #使用strip方法確定能尋找到所有元素,startwith,endwith按條件進行查找
    if l.strip().startswith(‘a‘or ‘A‘) and l.strip().endswith(‘c‘):
        #print(l.strip())
        list1.append(l.strip())
print(list1)

2、元組

tu = ("alc", " aric", "Alx", "Tny", "rain")
#找出的元素放到一個新列表中,因為元組中不能增加元素
list2 =[]
for l in tu:
    #使用strip方法確定能尋找到所有元素,startwith,endwith按條件進行查找
    #if 判斷遇到or和and是需要註意執行成功時的判斷
    if l.strip().startswith(‘a‘or ‘A‘) and l.strip().endswith(‘c‘):
        #print(l.strip())
        list2.append(l.strip())
print(list2)

3、字典

dic = {‘k1‘: "alx", ‘k2‘: ‘ aric‘,  "k3": "Alx", "k4": "Tny","k5":" Anc "}
#定義一個空字典
dic1 = {}
for k,v in dic.items():
    if (v.strip().startswith(‘a‘) or v.strip().startswith(‘A‘)) and v.strip().endswith(‘c‘):
        print(v)
        dic1[k] =v
print(dic1)

三、輸出商品列表,用戶輸入序號,顯示用戶選中的商品

#  商品
li = ["手機", "電腦", ‘鼠標墊‘, ‘鍵盤‘]
for num,v in enumerate(li,1):
     print(num,v)
choice = int(input("請選擇商品:"))
choice1=choice-1
if choice1>=0 and choice1<=len(li)-1:
    print(li[choice1])
else:
     print("商品不存在")

四、購物車
# 功能要求:
# 要求用戶輸入總資產,例如:2000
# 顯示商品列表,讓用戶根據序號選擇商品,加入購物車
# 購買,如果商品總額大於總資產,提示賬戶余額不足,否則,購買成功。
# 附加:可充值、某商品移除購物車
方法一:

goods = [
    {"product": "電腦", "price": 1999},
    {"product": "鼠標", "price": 10},
    {"product": "iphone", "price": 5000},
    {"product": "kindle", "price": 998},
]
#已經買到的商品
list_buy = []
#輸入總資產
all_money = 0
all_money = int(input("請輸入總資產:"))
#輸出所有的產品
for key,i in enumerate(goods,1):
    print(i[‘product‘],i[‘price‘])
#當條件成立時,在購買環節循環
while True:
    #選擇需要買的商品
    choice = input("請選擇商品(y/Y進行結算購買):")
    #是否進行結算
    if choice.lower() == "y":
        break

    #循環所有的商品與選擇商品進行對比,如果存在,就添加到list_buy中
    for v in goods:
        if choice == v["product"]:
            list_buy.append(v)
#輸出所有打算購買的商品
print(list_buy)
#定義商品總價初始值
total_price = 0
for p in list_buy:
    #計算所有商品價格
    total_price = total_price+p["price"]
if total_price>all_money:
    print("你的錢不夠,請充值%d元"%(total_price-all_money))
    chongzhi = int(input("輸入充值金額:"))
    all_money +=chongzhi
else:
    print("購買成功")
    print(list_buy)

方法二:

goods = [
    {"product": "電腦", "price": 1999},
    {"product": "鼠標", "price": 10},
    {"product": "iphone", "price": 5000},
    {"product": "kindle", "price": 998},
]
salary = int(input("請輸入工資:"))
#dic_shop_cart  = {"product":{"price":0,"num":0}}
dic_shop_cart = {}
#循環輸出所有產品
for p in goods:
    print(p[‘product‘],p[‘price‘])
while True:
    choice = input("請選擇購買的商品(y/Y進行結算):")
    if choice.lower() == ‘y‘:
        break
    #循環所有商品
    for item in goods:
        #判斷選擇的商品是否在所有商品中
        if item["product"] == choice:
            #如果存在,就把商品賦值給product
            product = item["product"]
            #如果商品在字典dic_shop_cart中,字典中num就加1
            if product in dic_shop_cart.keys():
                dic_shop_cart[product]["num"] = dic_shop_cart[product]["num"] + 1
                #如果不在,就第一次添加到字典中
            else:
                dic_shop_cart[product] = {"num":1,"single_price":item["price"]}
    print(dic_shop_cart)
sum_price = 0
for k,v in dic_shop_cart.items():
#    print(k,v)
    t_price = v["single_price"]*v["num"]
    print("購買%s的數量為%s:總價為%d"%(k,v["num"],t_price))
    sum_price=sum_price+t_price
print("所有商品總價為:%s"%sum_price)
if sum_price>salary:
    print("你的錢不夠,哈哈哈。。。,別買了吧")
else:
    print("購買成功,有錢人啊。。。")

輸出結果:

技術分享圖片
五、用戶交互,顯示省市縣三級聯動的選擇

dic = {
    "河北": {
        "石家莊": ["鹿泉", "槁城", "元氏"],
        "邯鄲": ["永年", "涉縣", "磁縣"],
    },
    "北京": {
        "大興": ["黃村", "清源", "天宮院"],
        "海澱": ["中關村", "西二旗", "五道口"],
    },
    "安徽": {
        "合肥": ["廬陽", "肥西", "濱湖"],
        "安慶": ["桐城", "宜秀區", "嶽西"],
    }
}
for p in dic:
    print(p)
p1 = input("請輸入省份:")
if p1 in dic.keys():
    for s in dic[p1]:
         print(s)
    s1 = input("請輸入市區:")
    if s1 in dic[p1].keys():
        for q in  dic[p1][s1]:
            print(q)
    else:
        print("市區還沒有錄入")
else:
    print("省份還沒有錄入")

執行結果:

技術分享圖片

python基本數據類型練習