首页 > 代码库 > 列表总结
列表总结
列表总结
#1,定义
a = [1,‘a‘,(3,4),‘hello‘]
#2,选取
a = [1,‘a‘,(3,4),(‘hello‘,)]
print a[0]
print a[2][0]
print a[3][0][1]
print a[1:3]
print a[:3]
print a[1:]
print a[:]
print a[0]
print a[-1]
#3,删除整个list
a = [1,‘a‘,(3,4),(‘hello‘,)]
print a
del a
print a
#4,删除某个元素
a = [1,‘a‘,(3,4),(‘hello‘,)]
print a
del a[0:1]
print a
#5,赋值
a = [1,‘a‘,(3,4),(‘hello‘,)]
print a
a[0] = 2
print a
#6,遍历
a = [1,‘a‘,(3,4),(‘hello‘,)]
for i in a:
print i
#7,方法
#L.append(var) 在尾部追加一个元素
a = [1,2]
a.append(3)
print a
#L.insert(index,var) 插入一个元素,参数1是下标,参数2是值
a = [1,2]
a.insert(0,3)
print a
#L.pop(var) 返回最后1个元素,并删除最后1个元素
a = [1,2]
b = a.pop()
print b,a
#L.remove(var) 删除第一次出现的该元素
a = [1,2,3,4,5,6,1]
a.remove(1)
print a
#L.count(var) 数数一共多少个某元素
a = [1,2,3,4,5,6,1]
print a.count(1)
#L.index(var) 返回某个下标的元素的值,参数是下标
a = [2,3,4,5,6,1]
print a.index(3)
#L.extend(list) 把参数里的列表的元素全都继承过来
a = [1,2,3]
b = [4,5,6]
a.extend(b)
print a
#L.sort() 排序
a = [1,3,2,4,6,5]
print a
a.sort()
print a
#L.reverse() 倒序,不是按大小排序,而是按下标的倒序进行排序
a = [1,3,2,4,6,5]
print a
a.reverse()
print a
#8,操作符 +
a = [1,2]
b = [3,4]
c = a + b
print c
#9,操作符 *
a = [1,2]
print a*3
#10,list的复制
a=[1,2]
b = a #b为a的别名,指针地址相同,对b操作即对a操作
a=[1,2]
b = a[:] #b为a的拷贝
列表总结