基础练习题
一、典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 方法一: 2 li = [11,22,33,44,55,66,77,88,99,90] 3 l1 = [] 4 l2 = [] 5 for i in li: 6 if i<= 66: 7 l1.append(i) #调用append方法,往后插入 8 else: 9 l2.append(i) 10 temp = {"k1":l1,"k2":l2} 11 print(temp) 12 13 方法二: 14 dic = { 15 "k1":[], 16 "k2":[], 17 } 18 for b in li: 19 if b <= 66: 20 dic["k1"].append(b) 21 else: 22 dic["k2"].append(b) 23 print(dic) 24 25 26 D:\Python35\python.exe D:/py_code/test.py 27 {'k2': [77, 88, 99, 90], 'k1': [11, 22, 33, 44, 55, 66]} 28 {'k2': [77, 88, 99, 90], 'k1': [11, 22, 33, 44, 55, 66]}
二、查找列表中元素,移除每个元素的空格,并查找以 a或A开头 并且以 c 结尾的所有元素。
li = ["alec", " aric", "Alex", "Tony", "rain"]
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 li = ["aleD", " aric", "Alex", "Tony", "rain"] 2 3 for i in li: 4 new_i = i.strip() #定义一个新变量才生效,否则不生效 5 if (new_i.startswith('a') or new_i.startswith('A')) and new_i.endswith('c'): 6 print(i) #和new_i 一样 7 8 9 D:\Python35\python.exe D:/py_code/test.py 10 aric
三、输出商品列表,用户输入序号,显示用户选中的商品
商品 li = ["手机", "电脑", '鼠标垫', '游艇']
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 li = ["手机", "电脑", '鼠标垫', '游艇'] 2 for i,j in enumerate(li): 3 print(i+1,j) 4 num = input("num:") 5 num = int(num) 6 len_li = len(li) 7 if num > 0 and num <= len_li: 8 good = li[num-1] 9 print(good) 10 else: 11 print("商品不存在") 12 13 14 15 D:\Python35\python.exe D:/py_code/test.py 16 1 手机 17 2 电脑 18 3 鼠标垫 19 4 游艇 20 num:4 21 游艇