编程语言
首页 > 编程语言> > Python列表操作与深浅拷贝(7)——列表深浅拷贝、删除、反转、排序

Python列表操作与深浅拷贝(7)——列表深浅拷贝、删除、反转、排序

作者:互联网

列表复制

浅拷贝:简单类型元素全复制,引用类型元素只复制引用

L1 = [3,2,1,[4,5,6],8,'abc']
L1
[3, 2, 1, [4, 5, 6], 8, 'abc']

L2 = L1.copy()
L2
[3, 2, 1, [4, 5, 6], 8, 'abc']
L1[3][1] = 10        #修改L1中的元素L2也随之变化
L1
[3, 2, 1, [4, 10, 6], 8, 'abc']
L2
[3, 2, 1, [4, 10, 6], 8, 'abc']

深拷贝:copy模块提供了deepcopy,引用类型完全复制为新元素

import copy
L3 = copy.deepcopy(L1)
L3
[3, 2, 1, [4, 10, 6], 8, 'abc']
L1[3][1] = 20
L1
[3, 2, 1, [4, 20, 6], 8, 'abc']
L3        #L3为深拷贝新生成的列表,修改L1元素对L3无影响
[3, 2, 1, [4, 10, 6], 8, 'abc']

*:对引用类型做浅拷贝处理

L4 = [[1,2,3]] * 3
L4
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]

L4[1][1] = 10
L4
[[1, 10, 3], [1, 10, 3], [1, 10, 3]]
for x in L4:
    print(x)
    print(id(x))        #取内存地址
[1, 10, 3]
84289032
[1, 10, 3]
84289032
[1, 10, 3]
84289032        #内存地址相同
L5 = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
L5
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]

for x in L5:
    print(x)
    print(id(x))
[1, 2, 3]
87157000
[1, 2, 3]
84213512
[1, 2, 3]
87157128

列表删除元素

remove(value) 基于元素查找,移除第一个出现的元素,并会引起列表元素移动O(n)

L6 = [3,2,1,4,5,6,7,2,3,4]
L6
[3, 2, 1, 4, 5, 6, 7, 2, 3, 4]

L6.remove(2)
L6
[3, 1, 4, 5, 6, 7, 2, 3, 4]

L6.remove(10)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-31-8cf95df45268> in <module>
----> 1 L6.remove(10)

ValueError: list.remove(x): x not in list

pop(index) 基于索引查找,移除索引位元素O(1),并会引起列表元素移动O(n)

L6.pop(3)
5 L6 [3, 1, 4, 6, 7, 2, 3, 4] L6.pop(10) L6 --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-33-8663c8410c3d> in <module> ----> 1 L6.pop(10) 2 L6 IndexError: pop index out of range

pop() 移除列表尾部一个元素O(1),效率高

L6.pop()
4 L6 [3, 1, 4, 6, 7, 2, 3]

clear() 清除列表所有元素,使列表长度为0,元素引用计数减1,剩下一个空列表

L6.clear()
L6
[]

列表翻转

reverse() 将列表元素反转,修改自身

L7 = [3,2,1,4,5,6,7,2,3,4]
L7
[3, 2, 1, 4, 5, 6, 7, 2, 3, 4]

L7.reverse()
L7
[4, 3, 2, 7, 6, 5, 4, 1, 2, 3]

列表排序

sort(key=function,reverse=True) 对列表元素排序,默认升序,修改自身

key指定不同类型元素如何排序,只在排序中使用,不修改元素

reverse=True为降序排序

L8 = [3,2,1,4,5,6,7,2,3,4,'a','b','c']
L8
[3, 2, 1, 4, 5, 6, 7, 2, 3, 4, 'a', 'b', 'c']

L8.sort()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-46-951f259be954> in <module>
----> 1 L8.sort()

TypeError: '<' not supported between instances of 'str' and 'int'

L8.sort(key=str,reverse=True)
L8
['c', 'b', 'a', 7, 6, 5, 4, 4, 3, 3, 2, 2, 1]

判断元素存在

in 判断元素在列表中是否存在,返回bool值

'c' in L8
True
4 in L8
True
10 in L8
False

标签:10,abc,元素,列表,L6,深浅,L1,拷贝
来源: https://www.cnblogs.com/omgasw/p/11613085.html