以中括号括起来,以","分隔每个元素,列表中的元素可以是数字,字符串,列表中可以嵌套列表。列表的列表中还能嵌套列表,也可以是布尔值。所有的都能放进去。
li = [1,12,9,"age",["hehe",2,"wang",["wanggang","xudong"]],"end"]
print(li[4][3][1])
---
xudong
---
切片
li = [1,12,9,"age",["hehe",2,"wang",["wanggang","xudong"]],"end"]
print(li[3:-1])
---
['age', ['hehe', 2, 'wang', ['wanggang', 'xudong']]]
# 取大于等于3,小于5
print(li[3:5])
---
['age', ['hehe', 2, 'wang', ['wanggang', 'xudong']]]
支持for循环,while循环,break,continue
for item in li:
print(item)
---
1
12
9
age
['hehe', 2, 'wang', ['wanggang', 'xudong']]
end
列表中的元素是可以被修改的,字符串不能被修改
li = [1,12,9,"age",["hehe",2,"wang",["wanggang","xudong"]],"end"]
li[1] = 250
print(li)
---
[1, 250, 9, 'age', ['hehe', 2, 'wang', ['wanggang', 'xudong']], 'end']
# 切片修改
li[1:3] = [250,500]
print(li)
---
[1, 250, 500, 'age', ['hehe', 2, 'wang', ['wanggang', 'xudong']], 'end']
可以被删除
del li[1]
print(li)
---
[1, 9, 'age', ['hehe', 2, 'wang', ['wanggang', 'xudong']], 'end']
# 通过切片删除
li = [1,12,9,"age",["hehe",2,"wang",["wanggang","xudong"]],"end"]
del li[4:-1]
print(li)
---
[1, 12, 9, 'age', 'end']
数字转字符串str()
字符串转数字int()
a = 123
int(a)
a = 123
str(a)
字符串转列表
a = "yangyajun"
print(list(a))
---
['y', 'a', 'n', 'g', 'y', 'a', 'j', 'u', 'n']
append追加
def append(self,p_object)
li = [11,22,33,44]
v = li.append(5)
print(v)
---
None
# 在原来值后追加
print(li)
---
[11,22,33,44,5]
清空
li.clear()
print(li)
---
[]
copy复制,浅拷贝
v = li.copy()
print(v)
---
[11,22,33,44]
计数count,计算元素出现的次数
v = li.count(22)
print(v)
---
2
iterable迭代,必须传一个可迭代对象
li = [11,22,33,22,44]
li.extend([9898,"不得了"])
print(li)
---
[11, 22, 33, 22, 44, 9898, '不得了']
index,根据值找索引(位置)
def index(self,value,start=None, stop=None):...
v = li.index(33)
print(v)
---
1
insert,根据指定位置(索引位置)插入元素
li = [11,22,33,22,44]
v = li.insert(0,99)
print(li)
---
[99, 11, 22, 33, 22, 44]
pop,默认把最后一个元素删除,并获取被删除的值
def pop(self,index=None)
li.pop()
print(li,v)
---
[11, 22, 33, 22] 44
# 根据索引的位置删除值,并获取,如果没有指定索引,默认是最后一个
v = li.pop(1)
print(li,v)
---
[11, 33, 22, 44] 22
remove,删除列中中指定值,左边优先
li.remove(22)
print(li,v)
---
[22, 33, 22, 44] None
将当前列表进行反转
li = [11,22,33,22,44]
li.reverse()
print(li)
---
[44, 22, 33, 22, 11]
排序
li = [11,44,22,33,22]
li.sort()
print(li)
---
[11, 22, 22, 33, 44]
# 从大到小排序
li.sort(revers=True)
---
[44, 33, 22, 22, 11]