首页 > 代码库 > Python练习题

Python练习题

一、元素分类

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

技术分享
l = [11,22,33,44,55,66,77,88,99,90]
ls1 = []
ls2 = []
for i in l:
    if i > 66:
        ls1.append(i)
    else:
        ls2.append(i)
print({k1:ls1,k2:ls2})
View Code
二、查找
查找列表中元素,移除每个元素的空格,并查找以 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"]
for i in li:
    l = i.strip()
    if (l.startswith(a) or l.startswith(A)) and l.endswith(c):
        print(l)

tu = ("alec", " aric", "Alex", "Tony", "rain")
for i in tu:
    l = i.strip()
    if (l.startswith(a) or l.startswith(A)) and l.endswith(c):
        print(l)

dic = {k1: "alex", k2:  aric,"k3": "Alex", "k4": "Tony"}
for key in dic:
    value1 = dic[key].strip()
    if (value1.startswith(a) or value1.startswith(A)) and value1.endswith(c):
        print(value1)
View Code
三、输出商品列表,用户输入序号,显示用户选中的商品
    商品 li = ["手机", "电脑", ‘鼠标垫‘, ‘游艇‘]
技术分享
li = ["手机", "电脑", 鼠标垫, 游艇]
l = []
for i in enumerate(li,1):
    l.append(i)
    user_choose = input(请输入你想要购买的商品序号: )
    if not user_choose.isdigit():continue
    print(l[int(user_choose)-1][1])
View Code

四、简单购物车

  实现打印商品详细信息,用户输入商品和购买个数,则将商品名,价格,购买个数加入购物列表,如果输入为空或其他非法输入,则要求用户重新输入

技术分享
for key in msg_dic:
    print(key, msg_dic[key])
while True:
        my_goods = input(请输入你想要购买的商品: )
        if my_goods not in msg_dic:continue
        my_count = input(请输入你想要购买的商品个数: )
        if  not my_count.isdigit():continue
        print((my_goods,msg_dic[my_goods],my_count))
        break
View Code

 

Python练习题