标签:
列表基础
列表定义:一有序数据集合用逗号间隔用方括号括起来
列表的索引访问(索引list_name[index]和切片list_name[start:end:step])
1 wu=[1,2,3,4] 2 print(wu[1]) 3 wu[1]=[5,6,7] 4 print(wu) 5 print(wu[1][1])
[root@localhost ~]# python 1.py 2 [1, [5, 6, 7], 3, 4] 6
列表遍历
1 wu=[1,2,3,4] 2 #### iteror 3 for i in wu: 4 print(i), 5 #print(i,) 6 #print(i) 7 print(‘‘) 8 i=0 9 while i<len(wu): 10 print(wu[i]), 11 i +=1
[root@localhost ~]# python 1.py 1 2 3 4 1 2 3 4
理解for迭代
1 a=range(1,10) 2 for x in a: 3 print(‘for‘,x) 4 a.pop(1) 5 print(a)
[root@localhost ~]# python 1.py (‘for‘, 1) [1, 3, 4, 5, 6, 7, 8, 9] (‘for‘, 3) [1, 4, 5, 6, 7, 8, 9] (‘for‘, 5) [1, 5, 6, 7, 8, 9] (‘for‘, 7) [1, 6, 7, 8, 9] (‘for‘, 9) [1, 7, 8, 9]
列表里的最大值
1 li=[23,45,55,66,743] 2 i=1 3 max=li[0] 4 while i<len(li): 5 if li[i]>max: 6 max=li[i] 7 i +=1 8 print(‘max‘,max) 9 print(‘###‘) 10 max=li[0] 11 for i in li: 12 if i>max: 13 max=i 14 print(‘max‘,max)
[root@localhost ~]# python 1.py (‘max‘, 743) ### (‘max‘, 743)
找第二大值
1 li=[23,45,55,66,743] 2 i=0 3 max1=li[0] 4 max2=li[0] 5 while i<len(li): 6 if max1<li[i]: 7 max2=max1 8 max1=li[i] 9 else: 10 if max2<li[i]: 11 max2=li[i] 12 i +=1 13 print(‘max1‘,max1) 14 print(‘max2‘,max2)
[root@localhost ~]# python 1.py (‘max1‘, 743) (‘max2‘, 66)
方法二:
1 li=[23,45,55,66,743] 2 i=0 3 max1=li[0] 4 max2=li[0] 5 for x in li: 6 if max1<x: 7 max2=max1 8 max1=x 9 else: 10 if max2<x: 11 max2=x 12 print(‘max1‘,max1) 13 print(‘max2‘,max2)
列表运算
列表加法
1 li1=[1,2,3] 2 li2=[4,5,6] 3 li=li1+li2 4 print(li)
[root@localhost ~]# python 1.py [1, 2, 3, 4, 5, 6]
1 li1=range(1,10) 2 li2=range(11,20) 3 print(li1) 4 print(li2) 5 i=0 6 while i <len(li1): 7 li1[i] += li2[i] 8 i +=1 9 print(li1)
[root@localhost ~]# python 1.py [1, 2, 3, 4, 5, 6, 7, 8, 9] [11, 12, 13, 14, 15, 16, 17, 18, 19] [12, 14, 16, 18, 20, 22, 24, 26, 28]
打印多层列表
index函数
1 li=range(1,11) 2 print(li) 3 print(li.index(6))
[root@localhost ~]# python 1.py [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 5
index函数
>>> li=range(1,11) >>> li [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> li[3:9] [4, 5, 6, 7, 8, 9] >>> li[-7:-1] [4, 5, 6, 7, 8, 9] >>> li[li.index(4):li.index(9)+1] [4, 5, 6, 7, 8, 9]
正负坐标的关系
>>> li=range(10,2100,2) >>> li[li.index(120):li.index(160)+1] [120, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160] >>> li[li.index(120)-len(li):li.index(160)+1-len(li)] [120, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160]
li=range(1,11)
1 >>> li[3:8] 2 [4, 5, 6, 7, 8] 3 >>> li[-7:-2] 4 [4, 5, 6, 7, 8] 5 >>> li[3:8:1] 6 [4, 5, 6, 7, 8] 7 >>> li[-7:-2:1] 8 [4, 5, 6, 7, 8] 9 >>> li[li.index(4):li.index(8)+1] 10 [4, 5, 6, 7, 8] 11 >>> li[li.index(8):li.index(4)-1:-1] 12 [8, 7, 6, 5, 4] 13 >>> li[:] 14 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 15 >>> li[::-1] 16 [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
标签:
原文地址:http://www.cnblogs.com/wujiadong2014/p/4965219.html