Home > Article > Backend Development > How to read arrays and lists in python
This time I will show you how to implement array and list reading in python. Notes on how to implement array and list reading in pythonare Which ones, the following are practical cases, let’s take a look.
In python, the ordinary list list is different from the array in numpy. The biggest difference is that a list can store different types of data, including int and float. and str, even Boolean; and the data types stored in an array must all be the same, int or float.
The data type in the list saves the address where the data is stored. Simply put, it is a pointer, not data. It is too troublesome to save a list in this way, for example, list1=[1,2,3,4 ] requires 4 pointers and four data, which increases storage and CPU consumption, while array1=numpy.array([1,2,3,4]) only needs to store four data, which is more convenient to read and calculate, so in When doing pure numerical operations, it is recommended to use array.
Precisely because lists can store different types of data, the size of each element in the list can be the same or different, so reading one column at a time is not supported, even for standard two-dimensional numbers. List:
>>> a=[[1,2,3],[4,5,6]] >>> a[0] #取一行 [1, 2, 3] >>> a[:,0] #尝试用数组的方法读取一列失败 TypeError: list indices must be integers or slices, not tuple
We need to use list parsing to read a column:
>>> b=[x[0] for x in a] >>> print(b) [1, 4]
For arrays, you can Direct reading:
>>> import numpy as np >>> a=np.array([[1,2,3],[4,5,6]]) >>> a[:,0] array([1, 4])
Of course lists also have unique advantages when dealing with mixed data.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Perfect solution to python2.7 being unable to use pip
How to implement Mahalanobis distance in Python
The above is the detailed content of How to read arrays and lists in python. For more information, please follow other related articles on the PHP Chinese website!