python自学第九天之作业

  • Post author:
  • Post category:python


1.有字符串"k:1|k1:2|k2:3|k3:4" 处理成字典{'k':1,'k1':2,'k2':3,'k3':4}
s = "k:1|k1:2|k2:3|k3:4"
dic = {}
c = s.split("|")
for i in c:
    k,v = i.split(":")
    dic[k] = int(v)
print(dic)
2.元素分类,有如下值li = [11,22,33,44,55,66,77,88,99,90],将所有大于66的值保存至字典的第一个key中,将小于66的值保存于第二个key中。
li = [11,22,33,44,55,66,77,88,99,90]
dic = {'k1':[],'k2':[]}
for i in li:
    if i == 66:
        continue
    elif i > 66:
        dic.setdefault('k1').append(i)
    else:
        dic.setdefault('k2').append(i)
print(dic)
3.输出商品列表,用户输入序号,显示用户选中的商品
 商品列表:
   goods = [{"name":"电脑","price":1999},
   {"name":"鼠标","price":10},
   {"name":"游艇","price":20},
   {"name":"美女","price"998},]
  要求:
   1)  页面显示 序号 + 商品名称 + 商品价格,如:
           1  电脑  1999
           2  鼠标  10
           ...
   2)  用户输入选择的商品序号,然后打印商品的名称及商品价格
   3)  如果用户输入的商品序号有误,则提示输入有误,并重新输入
   4)用户输入Q或者q,退出程序
goods = [{"name":"电脑","price":1999},
   {"name":"鼠标","price":10},
   {"name":"游艇","price":20},
   {"name":"美女","price":998},]
while 1:
    for i in goods:
        print(goods.index(i) + 1,i['name'],i['price'])
    user_input = input("请输入您要选择的商品序号,输入Q/q退出:")

    if user_input.isdigit() and 0 < int(user_input) < len(goods):
        i_index = int(user_input) - 1
        print(goods[i_index]['name'],goods[i_index]['price'])
    elif user_input.upper() == 'Q':
        break
    else:
        print('输入有误,请重新输入!')



版权声明:本文为pythonnot原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。