目录
lt = [1,2,3,4]
print(lt[1])
lt[1] = 3
print(lt)
2 [1, 3, 3, 4]
print(lt[:])#冒号左边没有左边取到头,右边没有则右边取到头
print(lt[1:2])#顾头不顾尾,只打印索引号为1的元素
print(lt[1:4:2])#步长为2
[1, 3, 3, 4] [3] [3, 4]
for i in lt:
print(i**2)#打印列表每一个值的幂
1 9 9 16
print(1 in lt)
print(5 in lt)
True False
lt.append(5)#往列表的最后一位添加元素
print(lt)
[1, 3, 3, 4, 5]
print(len(lt))
5
print(lt)
del lt[0]
print(lt)
[1, 3, 3, 4, 5] [3, 3, 4, 5]
lt=[1,2,3,4,5]
lt.insert(0,0)#向前插入
print(lt)
[0, 1, 2, 3, 4, 5]
lt = [11,22,33,44,55]
lt.pop(0)
print(lt)
[22, 33, 44, 55]
lt.remove(22)
print(lt)
[33, 44, 55]
lt = [11,11,11,22]
print(lt.count(11))
3
print(lt.index(11))#找到了就返回
0
lt = [1,2,3,4,5]
lt.clear()
print(lt)
[]
lt = [1,2,3,4]
lt1 = lt.copy()
print(lt1)
[1, 2, 3, 4]
lt1 = [1,2,3]
lt2 = [4,5,6]
lt1.extend(lt2)
print(lt1)
[1, 2, 3, 4, 5, 6]
lt = [1,2,3,4]
lt.reverse()
print(lt)
[4, 3, 2, 1]
sort() 函数用于对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数。
sort()方法语法:
list.sort(cmp=None, key=None, reverse=False)
lt = [2,3,1,0,4]
lt.sort(reverse=True)
print(lt)
[4, 3, 2, 1, 0]
有序or无序:有序
可变or不可变:可变
for i in range(len(lt)):
for j in range(len(lt)):
if lt[i]<lt[j]:
lt[i],lt[j] = lt[j],lt[i]
print(lt)
[0, 1, 2, 3, 4]