2020Python練習五
@2020.3.11
1、有串列['alex',49,[1900,3,18]],分別取出串列中的名字,年齡,出生的年,月,日賦值給不同的變數
>>> l=['alex',49,[1900,3,18]] >>> print('name:{name}\nage:{age}\nyear:{year}\nmonth:{month}\nday:{day}'.format(name=l[0],age=l[1],year=l[2][0], month=l[2][1],day=l[2][2])) name:alex age:49 year:1900 month:3 day:18 >>>
2、用串列的insert與pop方法模擬佇列
>>> d=[] >>> d.append(1) >>> d.append(2) >>> d.append(6) >>> print(d) [1, 2, 6] >>> print(d.pop()) 6 >>> print(d.pop()) 2 >>> print(d.pop()) 1 >>> print(d) [] >>>
3. 用串列的insert與pop方法模擬堆疊
>>> d=[] >>> d.insert(0,'cc')# insert(索引號,插入的值) >>> d.insert(1,'love') >>> d.insert(2,'mili') >>> print(d) ['cc', 'love', 'mili'] >>> print(d.pop()) mili >>> print(d.pop()) love >>> print(d.pop()) cc >>> print(d) [] >>>
4、簡單購物車,要求如下:
實作列印商品詳細資訊,用戶輸入商品名和購買個數,則將商品名,價格,購買個數以三元組形式加入購物串列,
如果輸入為慷訓其他非法輸入則要求用戶重新輸入
msg_dic={ 'apple':10, 'tesla':100000, 'mac':3000, 'lenovo':30000, 'chicken':10, }
purse_list = [] print("------------商品-----------") for k in msg_dic: print('商品:%s 單價:%s'% (k,msg_dic[k])) while True: product_name = input("請輸入需購買的商品(按q退出):").strip() if product_name.lower() == "q": break product_num = input("請輸入需購買商品個數:").strip() # 判斷商品和個數的合法性 if product_name in msg_dic: if product_num.isdigit(): product_num = int(product_num) # 將商品、價格、個數以元祖的形式加入購物串列, purse_tuple = (product_name,msg_dic[product_name],product_num) purse_list.append(purse_tuple) print(''' ----------------購物清單--------------- 商品:%s 單價:%s 數量:%s ----請保存好購物小票,祝您購物愉快------ ''' % (purse_tuple[0],purse_tuple[1],purse_tuple[2])) else: print("您輸入數量有誤") else: print("很抱歉,本店不出售該商品,")
5、有如下值集合 [11,22,33,44,55,66,77,88,99,90...],
將所有大于 66 的值保存至字典的第一個key中,將小于 66 的值保存至第二個key的值中
即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}
c={11,22,33,44,55,66,77,88,99,90}
dic={'k1':[],'k2':[]}
for x in c:
if x>66:
dic['k1'].append(x)
else:
dic['k2'].append(x)
print(dic)
6、統計s='hello alex alex say hello sb sb'中每個單詞的個數
s='hello alex alex say hello sb sb' res=s.split() print(res) for x in res: print(len(x))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/178308.html
標籤:Python
