1.有如下值集合[11,22,33,44,55,66,77,88,99,90], 将所有大于66的值保存至字典的第一个key中,将小于66值保存至第二个key的值
num = {11,22,33,44,55,66,77,88,99,90}
b1 =[]
b2 =[]
for i in num:
if i > 66:
b1.append(i)
if i < 66:
b2.append(i)
# 定义字典B
b = {"大于66": b1}
# 添加并赋值给b 有的话修改 没有的话添加
b["小于66"] = b2
print(b)
2.题. 输出商品列表,用户输入序号,显示用户选中的商品。
#商品 li = [“手机”, “电脑”, “鼠标垫”, “游艇” ]
a. 允许用户添加商品
li = ["手机", "电脑", "鼠标垫", "游艇" ]
li.append("衣服")
print(li)
b. 用户输入序号显示内容
enumerate索引编号和对应的元素组成的元祖
for i in enumerate(li,1):
print(i)
ret = int(input('请输入商品序列号:'))
print(li[ret-1])
3. 题.用户交互显示类似省市县N级联动的选择
#a. 允许用户增加内容
b. 允许用户选择查看某一个级别内容
dic = {
"河北": {
"石家庄": ["鹿泉", "藁城", "元氏"],
"邯郸": ["永年", "涉县", "磁县"],
},
"河南": {
"郑州":["上街区","二七区","金水区"],
"商丘":["永成","民权","宁陵"],
},
"山西": {
"大同":["大同","左云","广陵"],
"太原":["清徐","阳曲","娄烦"],
},
}
print("可查询省份:河北,河南,山西")
while True:
province = input('请输入省份包含的市: ').strip()
if province not in dic:
print('输入错误')
continue
elif len(province) == 0:
print('输入不正确')
continue
else:
for city in dic.get(province):
print(city)
your_choose = input('请输入市查看所有的县: ').strip()
print(dic.get(province).get(your_choose))
输出结果:
4.题 有两个列表 l1 = [11, 22, 33] l2 = [22, 33, 44]
a. 获取内容相同的元素列表
l1 = [11, 22, 33]
l2 = [22, 33, 44]
for i in l1:
for j in l2:
if i == j:
print(i)
结果:22 33
b. 获取l1中有, l2中没有的元素列表
for i in l1:
if i not in l2:
print(i)
结果:11
c. 获取l2 中有,l1中没有的元素列表
for i in l2:
for i not in l1:
print(i)
结果:44
d. 获取l1 和 l2 中内容都不同的元素
for i in l1:
if i not in l2:
print(i)
for i in l2:
if i not in l1:
print(i)
结果:11 44
5.转换列表-元组
a. 将字符串 s = "alex"转换为列表
s = "alex"
a = list(s)
print(a)
结果:[‘a’, ‘l’, ‘e’, ‘x’]
b. 将字符串s = "alex"转换为元组
s = "alex"
a = tuple(s)
print(a)
结果:(‘a’, ‘l’, ‘e’, ‘x’)
c. 将列表li = [“alex”, “seven”]转换为元组
li = ["alex", "seven"]
a = tuple(li)
print(a)
结果:(‘alex’, ‘seven’)
d. 将元组 tu = (“Alex”, “seven”)转换为列表
tu = ("Alex", "seven")
a = list(li)
print(a)
结果:[‘alex’, ‘seven’]