#把一个元素添加到列表的结尾,相当于 a[len(a):] = [x]。
a = [1,2,3,4]
a[len(a):] = [5] #a.append(5)
print("a = {a1}".format(a1=a)) #[1, 2, 3, 4, 5]
#通过添加指定列表的所有元素来扩充列表,相当于 a[len(a):] = L。
b = [1,2,3,4]
b.extend([5,6,7,8])
print("b = {b1}".format(b1=b))#[1, 2, 3, 4, 5, 6, 7, 8]
#在指定位置插入一个元素。第一个参数是准备插入到其前面的那个元素的索引,例如 a.insert(0, x) 会插入到整个列表之前,而 a.insert(len(a), x) 相当于 a.append(x) 。
c = [1,2,3,4]
c.insert(0,5)
print("c = {c1}".format(c1=c)) #[5, 1, 2, 3, 4]
# 删除列表中值为 x 的第一个元素。如果没有这样的元素,就会返回一个错误。
d = [1,2,3,4]
d.remove(4)
print("d = {d1}".format(d1=d))#[1, 2, 3]
# 从列表的指定位置移除元素,并将其返回。如果没有指定索引,a.pop()返回最后一个元素。元素随即从列表中被移除。(方法中 i 两边的方括号表示这个参数是可选的,而不是要求你输入一对方括号,你会经常在 Python 库参考手册中遇到这样的标记。)
e = [1,2,3,4]
e.pop()
print("e = {e1}".format(e1=e))
# 移除列表中的所有项,等于del a[:]。
f = [1,2,3,4]
f.clear()
print("f = {f}".format(f =f))#[]
# 返回列表中第一个值为 x 的元素的索引。如果没有匹配的元素就会返回一个错误。
g = [1,2,3,4]
print("g = {g1}".format(g1=g.index(4)))
# 返回 x 在列表中出现的次数。没有则返回0
h = [1,2,3,4,4]
print("h = {h1}".format(h1=h.count(5)))
# 对列表中的元素进行排序。
m = [4,3,6,5,1]
m.sort()
print("m = {m1}".format(m1=m))
# 倒排列表中的元素。
n = [1,2,3,4,5]
n.reverse()
print("n = {n1}".format(n1=n))
#返回列表的浅复制,等于a[:]。 放在新的数据地址中,只拷贝值。
m = [5,5,3,4,5]
m.copy()
a = m.copy()
b = m.copy()
print(id(m))
print(id(a))
print(id(b))
print(id(m))
输出结果:
D:\Software\Python\Python37\python.exe "D:/Software/PyCharm Community Edition 2018.3.5/py_code/test/Python0824/数据结构.py"
a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4, 5, 6, 7, 8]
c = [5, 1, 2, 3, 4]
d = [1, 2, 3]
e = [1, 2, 3]
f = []
g = 3
h = 0
m = [1, 3, 4, 5, 6]
n = [5, 4, 3, 2, 1]
2659643151816
2659643151688
2659639517832
2659643151816
Process finished with exit code 0