Home  >  Article  >  Backend Development  >  Detailed explanation of the comparison between list and NumPy.ndarry slicing in Python

Detailed explanation of the comparison between list and NumPy.ndarry slicing in Python

黄舟
黄舟Original
2017-07-24 15:23:232856browse

This article mainly introduces relevant information that explains the difference between Python list and NumPy.ndarry slicing. List slicing returns the original data, and modifications to the new data will not affect the original data, while NumPy.ndarry slicing does not. Friends who need to return the original data can refer to the following

Detailed explanation of the difference between Python list and NumPy.ndarry slice

Example code:


# list 切片返回的是不原数据,对新数据的修改不会影响原数据
In [45]: list1 = [1, 2, 3, 4, 5] 

In [46]: list2 = list1[:3]

In [47]: list2
Out[47]: [1, 2, 3]

In [49]: list2[1] = 1999

# 原数据没变
In [50]: list1
Out[50]: [1, 2, 3, 4, 5]

In [51]: list2
Out[51]: [1, 1999, 3]



# 而 NumPy.ndarry 的切片返回的是原数据
In [52]: arr = np.array([1, 2, 3, 4, 5])

In [53]: arr
Out[53]: array([1, 2, 3, 4, 5])

In [54]: arr1 = arr[:3]

In [55]: arr1
Out[55]: array([1, 2, 3])

In [56]: arr1[0] = 989

In [57]: arr1
Out[57]: array([989,  2,  3])

# 修改了原数据
In [58]: arr
Out[58]: array([989,  2,  3,  4,  5])

# 若希望得到原数据的副本, 可以用 copy()
In [59]: arr2 = arr[:3].copy()

In [60]: arr2
Out[60]: array([989,  2,  3])

In [61]: arr2[1] = 99282

In [62]: arr2
Out[62]: array([ 989, 99282,   3])

# 原数据没被修改
In [63]: arr
Out[63]: array([989,  2,  3,  4,  5])

The above is the detailed content of Detailed explanation of the comparison between list and NumPy.ndarry slicing in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn