作业一:将字符串”k:1/k1:2/k2:3/k3:4”处理成字典(比较难)
方法1
list = 'k:1/k1:2/k2:3/k3:4'
new_list = list.split("/")
print(new_list)
dic = {}
for i in new_list:
k,v = i.split(":")
dic[k] = int(v)
print(i)
print(dic)
方法2
list = []
list_key = []
list_value = []
str = "k:1/k1:2/k2:3/k3:4"
str = str.split('/')
for i in str:
l = i.split(':')
list.append(l)
for j in list:
list_key.append(j[0])
list_value.append(j[1])
d = dict(zip(list_key,list_value))
print(d)
作业二:有如下list=[11,22,33,44,55,66,77,88,99],将所有大于55的值保存在字典的第一个key中,将小于55的值保存至第二个key中。形式如下:{“k1”:[n>55],”k2”:[n<55]}
方法1
list=[11,22,33,44,55,66,77,88,99]
dic ={'k1':[],'k2':[]}
for i in list:
if i == 55:
continue
elif i > 55:
dic.setdefault('k1').append(i)
else:
dic.setdefault('k2').append(i)
print(dic)
方法2
list1 = []
list2 = []
list_key = ['k1','k2']
list_value = []
list=[11,22,33,44,55,66,77,88,99]
for i in list:
if i >= 55:
list1.append(i)
else:
list2.append(i)
list_value.append(list1)
list_value.append(list2)
d = dict(zip(list_key,list_value))
print(d)
作业三:显示下面表格,做出如下功能
序号 | 名称 | 价格 |
---|
1 | 小米MIX | 5799 | 2 | 华为P40 | 5999 | … … | … … | … … |
功能1:用户输入选择序号,自动打印出名称和价格
功能2:输入序号有误,提示、重新输入
功能3:输入 q或者 Q,退出程序
方法1
goods = [{'name': "小米MIX", 'price': 5799},
{'name': '华为P40', 'price': 5999},
{'name': 'phone', 'price': 1000},
{'name': 'video', 'price': 999}]
for i in goods:
print(goods.index(i) + 1 ,i['name'],i['price'])
while True:
str_input = input('输入你想要的商品的序号,当输入Q/q退出系统:')
if str_input.isdigit() and 0 < int(str_input) <= len(goods):
a = int(str_input) -1
print(goods[a]['name'],goods[a]['price'])
elif str_input.upper() == 'Q':
print('退出程序成功')
break
else:
print("输入有误,请重新选择")
方法2
list_serial = ['1','2']
list_name = ['小米MIX','华为P40']
list_price = ['5799','5999']
d1 = dict(zip(list_serial,list_name))
d2 = dict(zip(list_name,list_price))
def info(n):
if d1.get(n) != None:
print("你想买的商品信息为:","name:",d1.get(n),"|","price:",d2.get(d1.get(n)))
else:
print("输入序号有误,请重新输入")
if __name__ == '__main__':
while True:
n = input('请输入要查询商品信息的序号:')
if n.upper() == "Q":
print("退出程序成功")
break
else:
info(n)
|