python基礎資料型別 (Elementary Data Type)練習

來源:互聯網
上載者:User

標籤:img   with   class   結果   png   資產   +=   blog   集合   

一、元素分類
# 有如下值集合 [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] =vprint(dic1)

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

#  商品li = ["手機", "電腦", ‘滑鼠墊‘, ‘鍵盤‘]for num,v in enumerate(li,1):     print(num,v)choice = int(input("請選擇商品:"))choice1=choice-1if 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 = 0all_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 = 0for 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 +=chongzhielse:    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 = 0for 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_priceprint("所有商品總價為:%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基礎資料型別 (Elementary Data Type)練習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.