1.将列表的每一个元素拼接成字符串 li = ["第一",2,"ss",55] test = "" for l in li : test+=str(l) print(test) 2.查找列表中元素,移除每个元素的空格,并查找以a或A开头并且以c结尾的所有元素 li = ["a lec", " ar ic", "A lex", "Tony ", "ra in"] i = 0 while i<len(li) : li[i]=li[i].replace(" ","") if li[i].startswith("a")==True or li[i].startswith("A")==True and li[i].endswith("c")==True : print(li[i]) i+=1 else: i +=1 print(li) 3 tu=('alex', 'eric', 'rain') print(len(tu)) print(tu[1]) print(tu[:2]) for t in tu : print(t) for i in range(len(tu)) : print(i) for i in enumerate(tu,10) : print(i) 4 dic = {'k1': "v1", "k2": "v2", "k3": [11,22,33]} for di in dic: print(di) for di in dic.values(): print(di) for k,v in dic.items(): print(k,v) dic.setdefault("k4","v4") dic.update({"k1":"alex"}) dic.get("k3").append(44) dic.get("k3").insert(0,18) for k,v in dic.items(): print(k,v) 5将列表li = ["alex", "seven"]转换成字典且字典的key按照10开始向后递增 li = ["alex", "seven"] tu = {} for k,v in enumerate(li,10): tu[k]=v print(tu) 6有如下值集合[11,22,33,44,55,66,77,88,99,90],将所有大于66的值保存至字典的第一个key中,将小于66的值保存至第二个key的值中。 即:{'k1':大于66的所有值, 'k2':小于66的所有值} li = [11,22,33,44,55,66,77,88,99,90] sorut = {"k1":[],"k2":[],} for l in li : if l>66 : sorut["k1"].append(l) elif l<66 : sorut["k2"].append(l) else: pass print(sorut) 7输出商品列表,用户输入序号,显示用户选中的商品 商品li = ["手机", "电脑", '鼠标垫', '游艇'] 允许用户添加商品 用户输入序号显示内容 li = ["手机", "电脑", '鼠标垫', '游艇'] print('商品列表'.center(20,'-')) i=0 re =True # while i<len(li): # i+=1 # print(i,li[i-1]) while re: in1 = input("选择操作:1添加 2序号查找") if in1=="1": add = input("添加商品:") li.append(add) re=False elif in1 =="2": num = input("序号:") if int(num)>len(li): print("序号错误!") num = input("请重新输入序号:") else: print(li[int(num)-1]) re=False else: print("请输入正确操作!") while i<len(li): i+=1 print(i,li[i-1]) 8 for ran in range(1,101): print(ran) for ran in range(100,0,-1): print(ran) i = 0; while i<100: i+=1 print(i) a=100 while a>0: print(a) a-=1 9 9x9 for i in range(1,10): for j in range(1,i+1): print(str(j)+"X"+str(i)+"="+str(i*j),end=" ") print() 10 一百以内的素数 trun = True ret = [] for i in range(1,101): j=2 while trun and j<i: if i%j!=0: j+=1 else: trun=False if trun==True: ret.append(i) trun=True else: trun=True print(sum(ret)) 冒泡 li = [1,3,2,7,6,23,41,24,33,85,56] temp = 0 for l in range(0,len(li)): for j in range(0,l): if li[j]>li[l]: li[l],li[j]=li[j],li[l] print(li) 公鸡母鸡小鸡 100元 公鸡 = 5 母鸡 = 3 小鸡 = 2 for g in range(1,20): for m in range(1,33): for x in range(1, 50): if 5*g+3*m+2*x==100: print(g,m,x)
Python 基础练习二
最新推荐文章于 2022-08-12 10:31:09 发布