#定义一个字典d,键分别为a1,a2,值分别为列表[1,3,4]和元组(3,5,6)d={'a1':[1,3,4],'a2':(3,5,6)}'''字典定义:{元素1,元素2,……},元素是由“键:值"组成'''
#对列表a切片,分别切出1、[1,2]、[1,3]a=[1,2,3,4,5,6]a1=a[0]a2=a[0:2]a3=a[0:3:2]'''列表切片方式:a:b:c,对应[a,b),步长为c,如果c=1,缺省'''#对元组b切片,分别切出1、(1,2)、(1,3)b=(1,2,3,4,5,6)b1=b[0]b2=b[0:2]b3=b[0:3:2]#对字符串c切片,分别切出'h'、'he'、'hlo'c='hello world!'c1=c[0]c2=c[0:2]c3=c[0:5:2]#对字典d切片,分别切出a、c键对应的值d={'a':[1,4,5],'b':(1,2,3),'c':[7,8,9],'d':'hello world'}d1=d['a']d2=d['c']
3.列表常用函数append和extend使用示例#建立含有3和Python的列表L1,并将L2添加到L1后面L2=[1,2,3,4]#L1=[3,'ptyhon']L1=[]L1.append(3)L1.append('ptyhon')L1.extend(L2)'''append---依次添加元素到列表中extend---整体将某个列表添加到另外一个列表中'''
4.字典创建(setdefault函数)和for循环综合使用示例#给出一个嵌套列表L#定义一个空字典D#用for循环方式将列表L中的元素作为值依次填充至字典D中#其中标识键用a,b,c,d来表示,并返回计算结果DL=[5,[4,'myself'],(1,2,4),'learn']key=['a','b','c','d']D={}'''D.setdefault('a',5)D.setdefault('b',[4,'myself'])D.setdefault('c',(1,2,4))D.setdefault('d','learn')'''for i in range(4): D.setdefault(key[i],L[i])
#利用条件语句实现成绩的分级#其中90~100为优秀,80~89为良好#70~79为中等,60~69为及格,0~59为不及格#今有成绩为85分,请输出成绩等级t=85'''#1. if 条件: 执行的语句块(左对齐)#2. if 条件1: 执行语句块1(左对齐) elif 条件2: 执行语句块2(左对齐) elif 条件3: 执行语句块3(左对齐) …… elif 条件n: 执行语句块n(左对齐) else: 执行语句块n+1(左对齐)条件1,条件2……,条件n,不相交(相互独立),else执行的语句条件,否则……(即不满足上述n个条件之外的,就执行)#3. if 条件1: 执行语句块1(左对齐) else: 执行语句块2(左对齐)满足条件1,执行其语句块1,否则执行执行语句块2''''''if t>=90 and t<=100: print('优秀')if t>=80 and t<=89: print('良好')if t>=70 and t<=79: print('中等')if t>=60 and t<=69: print('及格')if t>=0 and t<=59: print('不及格')''''''if t>=90 and t<=100: print('优秀')elif t>=80 and t<=89: print('良好')elif t>=70 and t<=79: print('中等')elif t>=60 and t<=69: print('及格')else: print('不及格')'''v=-9import mathif v>=0: print(math.sqrt(v))else: print('负数不能开根号')
#用for循环依次获得2017年11月和12月的自然日期,并分别用列表L1和L2来存储#注意:日期格式为长度10的字符串,比如“2017-11-02”。'''字符串的连接符:“+”year='2017'month='11'day='02'print(year+month+day)20171102s1='-'print(year+s1+month+s1+day)2017-11-02字符串的连接:要求连接的每个变量必须是字符串类型year='2017'month=11day='02'print(year+s1+str(month)+s1+day)month=str(month)print(year+s1+month+s1+day)'''L1=[]L2=[]for i in range(1,31): if i<=9: d='0'+str(i) else: d=str(i) res='2017-11-'+d L1.append(res)for i in range(1,32): if i<=9: d='0'+str(i) else: d=str(i) res='2017-12-'+d L2.append(res)
#将列表L中的经纬度字符型数据按经度和纬度拆分出来并转换为数值类型#分别存储为两个不同的列表L1和L2L=['113.980 22.566', '113.940 22.686', '113.957 22.576', '114.244 22.564']L1=[]L2=[]'''s1=L[0]j=s1[0:7]w=s1[8:14]L1.append(float(j))L2.append(float(w))s1=L[1]j=s1[0:7]w=s1[8:14]L1.append(float(j))L2.append(float(w))s1=L[2]j=s1[0:7]w=s1[8:14]L1.append(float(j))L2.append(float(w))for i in range(4): s1=L[i] j=s1[0:7] w=s1[8:14] L1.append(float(j)) L2.append(float(w))''''''s-------字符串在s中查找字符出现的位置,用户find函数,用法为:index=s.find(s1,a1,b1)s1--待查的字符或字符串a1--开始位置(针对s)b1--结束位置(针对s)一般情况下,我们查找s1在s中出现的位置,从开头查找到结尾s1=L[1]indx=s1.find(' ',0,len(s1))'''for i in range(len(L)): s1=L[i] indx=s1.find(' ',0,len(s1)) j=s1[:indx] w=s1[indx+1:] L1.append(float(j)) L2.append(float(w))