List浅拷贝深拷贝切片

Posted LeeeetMe

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了List浅拷贝深拷贝切片相关的知识,希望对你有一定的参考价值。

一、List:是Python内置的数据类型列表--List,List是一种有序集合,可以随时删除和添加元素。

创建list直接用 []
1
letters = ["a","b","c","d","e"] 2 0 1 2 3 4 3 print(letters[0]) 4 a 5 print(letters[1]) 6 b 7 #list中是通过索引来获取列表中的元素,索引是从0开始

如果说想要直接获取list的最后一个元素可以直接用-1的索引获取

1 >>> letters[-1]
2 e
3 >>> letters[-2]
4 d
5 >>> 

通过len()函数可以来获取列表中有多少个元素

>>> len(letters)
5
letters列表中有5个元素

List也是有相应的方法:

append():在List最后一位添加元素

>>> letters.append("F")
>>> print(letters)
[a, b, c, d, e, F]

clear():清空List

>>> letters = ["a","b","c","d","e",]
>>> letters.clear()
>>> print(letters)
[]

count(value):在列表中该元素的个数

>>> letters = ["a","b","c","d","e","e","e"]
>>> letters.count("e")
3

extend():扩展List,添加到该List的末尾

>>> letters = ["a","b","c","d","e"]
>>> numbers = [1,2,3,4,5]
>>> letters.extend(numbers)
>>> print(letters)
[a, b, c, d, e, 1, 2, 3, 4, 5]

index():查找第一个出现的该元素在列表中的索引

>>> letters = ["a","b","c","d","e","e","e"]
>>> letters.index("e")
4

insert(index,p_object):在List中添加元素

>> letters = ["a","b","c","d","e"]
>>> letters.insert(1,"A")
>>> print(letters)
[a, A, b, c, d, e]

pop(index = None):通过索引删除病返回List中的元素,如果没有输入参数则默认删除List最后一个元素

>>> letters.pop()
e
>>> letters.pop(3)
d
>>> print(letters)
[a, b, c]

remove(value):删除List中第一个出现的该元素

>>> letters = ["a","b","c","d","e","e","e"]
>>> letters.remove("e")
>>> print(letters)
[a, b, c, d, e, e]

reverse():倒转List

>>> letters = ["a","b","c","d","e"]
>>> letters.reverse()
>>> print(letters)
[e, d, c, b, a]

sort():将List中的元素从小到大排序

","f","d","a","e","5","e","e","2","$#aa"]
>>> letters.sort()
>>> print(letters)
[$#aa, 2, 5, 6, a, d, e, e, e, f]
>>> 

二、浅拷贝,深拷贝

留坑:填

三、切片

关于切片,最初可能有些迷惑,但总结后思路就特别清晰:

[起始:结束:方向/间隔]

>>> letters = ["6","f","d","a","e","5","e","e","2","$#aa",2,4,2,4,5,66,7,33]
>>> letters[1:12:3] #表示从索引为1的元素开始取值,到索引12结束(不包括索引12的元素),间隔为3
[f, e, e, 2]


[起始:结束:方向/间隔] 注意:如果想倒序切片,需要把"方向/间隔"改成负数

>>> letters = ["6","f","d","a","e","5","e","e","2","$#aa",2,4,2,4,5,66,7,33]
>>> letters[12:1:-3]
[2, $#aa, e, a]

 

以上是关于List浅拷贝深拷贝切片的主要内容,如果未能解决你的问题,请参考以下文章

python_深拷贝与浅拷贝

浅拷贝与深拷贝

切片操作会给我一个深拷贝还是浅拷贝?

深拷贝,浅拷贝

深拷贝与浅拷贝

python的深拷贝与浅拷贝