List operations and precautions in python

【Pit encountered】

Directly use '=' to make the two lists equal, that is: b=a, then when a is changed, b will also change

>>> a = [1, 2, 3]

>>> b = a

>>> print b

[1, 2, 3]

>>> a[0] = 0

>>> print b

[0, 2, 3]    

Explanation: [1, 2, 3] is regarded as an object, a, b are references to this object, therefore, changing a[0], b also changes


※ To avoid this, there are two ways to avoid it.

1. Use list slice A = B[:]

2. Deep copy A = copy.deepcopy(B)

An example of the use of slices:

>>> b = a[:]

>>> a[0] = 0

>>> print b

[1, 2, 3]

Explanation: Slicing a[:] will generate a new object, occupying a new memory, and b points to this new memory area, so changing the value of the object pointed to by a will not affect b


List deep copy and shallow copy

shallow copy

>>> import copy

>>> a = [1, 2, 3, [5, 6]]

>>> b = copy.copy(a)

>>> print b

[1, 2, 3, [5, 6]]

>>> a[3].append('c')

>>> print b

[1, 2, 3, [5, 6, 'c']]  

deep copy

>>> a = [1, 2, 3, [5, 6]]

>>> b = copy.deepcopy(a)

>>> a[3].append('c')

>>> print b

[1, 2, 3, [5, 6]]

A deep copy is to open up a new memory space and copy the value in the copied object. Since a new space is opened up, changing the value of [5, 6] in a does not affect b.

The shallow copy does not open up a new memory space for the sub-object [5, 6], but only implements a reference to [5, 6] in a. So change the value of [5, 6] in a, and the value in b will also change.


※Array assignment cannot use slices for the same purpose

>>> import numpy as np

>>> a = np.array([1, 2 ,3])

>>> b = a[:]

>>> a[0] = 5

>>> print a, b

[5 2 3] [5 2 3]

如上,虽然用切片,但不能达到修改a而不影响b的目的。说明a,b仍然指向同一块内存。

此时,只能用拷贝

>>> b = a.copy()

>>> a[0] = 5

>>> print a, b

[5 2 3] [1 2 3]

此时修改a不会影响到b。

注意,列表的拷贝是copy.copy(obj)或copy.deepcopy(obj),数组的拷贝是obj.copy()


【1】将字符串转化为list:

(字符串(str)转化为list和tuple,list和tuple之间相互转化)

>>> s = "xxxxx"
>>> list(s)
['x', 'x', 'x', 'x', 'x']
>>> tuple(s)
('x', 'x', 'x', 'x', 'x')
>>> tuple(list(s))
('x', 'x', 'x', 'x', 'x')
>>> list(tuple(s))

['x', 'x', 'x', 'x', 'x']

(将list或者tuple转化为str)

>>> "".join(tuple(s))
'xxxxx'
>>> "".join(list(s))
'xxxxx'
>>> str(tuple(s))
"('x', 'x', 'x', 'x', 'x')"
>>> 

【2】删除列表中的元素

li = [1,2,3,4,5,6]
>>>使用del删除对应下标的元素
del li[2]
>li = [1,2,4,5,6]
>>>使用.pop()删除最后一个元素
li.pop()
>li = [1,2,4,5]
>>>删除指定值的元素(remove后面括号中的内容是list中的具体元素,不是index)
li.remove(4)
>li = [1,2,5]
>>>使用切片来删除
li = li[:-1]
>li = [1,2]
# !!!切忌使用这个方法,如果li被作为参数传入函数,
那么在函数内使用这种删除方法,将不会改变原list
    li = [1,2,3,4,5,6]
def delete(li, index):
     li = li[:index] + li[index+1:]
delete(li, 3)
print li
# 会输出[1,2,3,4,5,6]

参考:https://www.douban.com/note/277146395/

          https://blog.csdn.net/sruru/article/details/7803208

          https://blog.csdn.net/lc_lc2000/article/details/53135839

其他相关操作:http://www.runoob.com/python/python-lists.html

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326693256&siteId=291194637