Python machine learning library NumPy
When we use Python language for machine learning programming, this is a very commonly used basic library. This article is an introductory tutorial for the Python machine learning library NumPy. Interested friends should learn together
NumPy is a Python language software package, which is very suitable for scientific computing. This is a very commonly used basic library when we use Python language for machine learning programming.
This article is an introductory tutorial to it.
Introduction
NumPy is a basic software package for scientific and technological computing, which is implemented in Python language. It contains:
Powerful N-dimensional array structure
Sophisticated and complex functions
Tools that can be integrated into C/C and Fortran code
Linear algebra, Fourier transform, and random number capabilities
In addition In addition to scientific computing, NumPy can also be used as an efficient multi-dimensional container for general-purpose data. Because it works with any type of data, this allows NumPy to be seamlessly and efficiently integrated into many types of databases.
Get NumPy
Since this is a Python language software package, you need to have the Python language on your machine first environment of. Regarding this, please search the Internet for how to obtain it yourself.
For how to obtain NumPy, please also refer to the Installing packages on the scipy.org official website. This article will not go into details.
The author recommends using pip to install the Python package. The command is as follows:
pip3 install numpy
The code of this article is as follows Verified and tested in environment:
Hardware: MacBook Pro 2015
OS: macOS High Sierra
Language environment: Python 3.6.2
Package: numpy 1.13.3
You can get this article here All source codes: https://github.com/paulQuei/numpy_tutorial
In addition,
For the sake of simplicity, in this article we will use Python’s print function to obtain the results. Verification
For spelling convenience, we will import numpy as np by default
Basic attributes and array creation
The basis of NumPy is a homogeneous multidimensional data, and the elements in the array can be indexed by subscripts. In NumPy, the dimension is called axis (the plural is axes), and the number of dimensions is called rank.
For example:
The following is an array with rank 1 and the length of axis is 3:
[1, 2, 3]
The following is an array with rank 2, and the length of axis is also 3:
[[ 1, 2, 3],
[ 4, 5, 6]]
We can create NumPy arrays through the array function, for example:
a = np.array([1, 2, 3]) b = np.array([(1,2,3), (4,5,6)])
Please note that the square brackets here are required, The following way of writing is wrong:
a = np.array(1,2,3,4) # WRONG!!!
NumPy’s array class is ndarray, and its alias is numpy.array, but This is not the same as the Python standard library's array.array. The latter is just a one-dimensional array. And ndarray has the following attributes:
ndarray.ndim: The dimension of the array. In the Python world, the dimension is called rank
ndarray.shape: the dimension of the array. This is a sequence of numbers, the length of which is determined by the array's dimensions (ndim). For example: the shape of a one-dimensional array of length n is n. The shape of a matrix with n rows and m columns is n,m
ndarray.size: the number of all elements in the array
- ##ndarray.dtype : The type of elements in the array, such as numpy.int32, numpy.int16 or numpy.float64
- ndarray.itemsize: The size of each element in the array, in bytes
- ndarray.data: Buffer to store array elements. Usually we only need to access elements through subscripts, without accessing the buffer
# create_array.py
import numpy as np
a = np.array([1, 2, 3])
b = np.array([(1,2,3), (4,5,6)])
print('a=')
print(a)
print("a's ndim {}".format(a.ndim))
print("a's shape {}".format(a.shape))
print("a's size {}".format(a.size))
print("a's dtype {}".format(a.dtype))
print("a's itemsize {}".format(a.itemsize))
print('')
print('b=')
print(b)
print("b's ndim {}".format(b.ndim))
print("b's shape {}".format(b.shape))
print("b's size {}".format(b.size))
print("b's dtype {}".format(b.dtype))
print("b's itemsize {}".format(b.itemsize))a= [1 2 3] a's ndim 1 a's shape (3,) a's size 3 a's dtype int64 a's itemsize 8 b= [[1 2 3] [4 5 6]] b's ndim 2 b's shape (2, 3) b's size 6 b's dtype int64 b's itemsize 8
c = np.array( [ [1,2], [3,4] ], dtype=complex )
Note: NumPy itself supports multi-dimensional arrays and also supports data of various types of elements. However, considering that array structures of three dimensions and above are not easy to understand, and when we program machine learning, we use matrix operations most. Therefore, the following examples in this article mainly use one-dimensional and two-dimensional numerical arrays for illustration.
Creation of specific array
- zeros: used to create an array with all elements being 0
- ones: Used to create an array whose elements are all 1
empty:用来创建未初始化的数据,因此是内容是不确定的
arange:通过指定范围和步长来创建数组
linespace:通过指定范围和元素数量来创建数组
random:用来生成随机数
# create_specific_array.py
import numpy as np
a = np.zeros((2,3))
print('np.zeros((2,3)= \n{}\n'.format(a))
b = np.ones((2,3))
print('np.ones((2,3))= \n{}\n'.format(b))
c = np.empty((2,3))
print('np.empty((2,3))= \n{}\n'.format(c))
d = np.arange(1, 2, 0.3)
print('np.arange(1, 2, 0.3)= \n{}\n'.format(d))
e = np.linspace(1, 2, 7)
print('np.linspace(1, 2, 7)= \n{}\n'.format(e))
f = np.random.random((2,3))
print('np.random.random((2,3))= \n{}\n'.format(f))这段代码的输出如下
np.zeros((2,3)= [[ 0. 0. 0.] [ 0. 0. 0.]] np.ones((2,3))= [[ 1. 1. 1.] [ 1. 1. 1.]] np.empty((2,3))= [[ 1. 1. 1.] [ 1. 1. 1.]] np.arange(1, 2, 0.3)= [ 1. 1.3 1.6 1.9] np.linspace(1, 2, 7)= [ 1. 1.16666667 1.33333333 1.5 1.66666667 1.83333333 2. ] np.random.random((2,3))= [[ 0.5744616 0.58700653 0.59609648] [ 0.0417809 0.23810732 0.38372978]]
Shape与操作
除了生成数组之外,当我们已经持有某个数据之后,我们可能会需要根据已有数组来产生一些新的数据结构,这时候我们可以使用下面这些函数:
reshape:根据已有数组和指定的shape,生成一个新的数组
vstack:用来将多个数组在垂直(v代表vertical)方向拼接(数组的维度必须匹配)
hstack:用来将多个数组在水平(h代表horizontal)方向拼接(数组的维度必须匹配)
hsplit:用来将数组在水平方向拆分
vsplit:用来将数组在垂直方向拆分
下面我们通过一些例子来进行说明。
为了便于测试,我们先创建几个数据。这里我们创建了:
zero_line:一行包含3个0的数组
one_column:一列包含3个1的数组
a:一个2行3列的矩阵
b:[11, 20)区间的整数数组
# shape_manipulation.py
zero_line = np.zeros((1,3))
one_column = np.ones((3,1))
print("zero_line = \n{}\n".format(zero_line))
print("one_column = \n{}\n".format(one_column))
a = np.array([(1,2,3), (4,5,6)])
b = np.arange(11, 20)
print("a = \n{}\n".format(a))
print("b = \n{}\n".format(b))通过输出我们可以看到它们的结构:
zero_line = [[ 0. 0. 0.]] one_column = [[ 1.] [ 1.] [ 1.]] a = [[1 2 3] [4 5 6]] b = [11 12 13 14 15 16 17 18 19]
数组b原先是一个一维数组,现在我们通过reshape方法将其调整成为一个3行3列的矩阵:
# shape_manipulation.py
b = b.reshape(3, -1)
print("b.reshape(3, -1) = \n{}\n".format(b))这里的第二参数设为-1,表示根据实际情况自动决定。由于原先是9个元素的数组,因此调整后刚好是3X3的矩阵。这段代码输出如下:
b.reshape(3, -1) = [[11 12 13] [14 15 16] [17 18 19]]
接着,我们通过vstack函数,将三个数组在垂直方向拼接:
# shape_manipulation.py
c = np.vstack((a, b, zero_line))
print("c = np.vstack((a,b, zero_line)) = \n{}\n".format(c))这段代码输出如下,请读者仔细观察一下拼接前后的数据结构:
c = np.vstack((a,b, zero_line)) = [[ 1. 2. 3.] [ 4. 5. 6.] [ 11. 12. 13.] [ 14. 15. 16.] [ 17. 18. 19.] [ 0. 0. 0.]]
同样的,我们也可以通过hstack进行水平方向的拼接。为了可以拼接我们需要先将数组a调整一下结构:
# shape_manipulation.py
a = a.reshape(3, 2)
print("a.reshape(3, 2) = \n{}\n".format(a))
d = np.hstack((a, b, one_column))
print("d = np.hstack((a,b, one_column)) = \n{}\n".format(d))这段代码输出如下,请再次仔细观察拼接前后的数据结构:
a.reshape(3, 2) = [[1 2] [3 4] [5 6]] d = np.hstack((a,b, one_column)) = [[ 1. 2. 11. 12. 13. 1.] [ 3. 4. 14. 15. 16. 1.] [ 5. 6. 17. 18. 19. 1.]]
请注意,如果两个数组的结构是不兼容的,拼接将无法完成。例如下面这行代码,它将无法执行:
# shape_manipulation.py # np.vstack((a,b)) # ValueError: dimensions not match
这是因为数组a具有两列,而数组b具有3列,所以它们无法拼接。
接下来我们再看一下拆分。首先,我们将数组d在水平方向拆分成3个数组。然后我们将中间一个(下标是1)数组打印出来:
# shape_manipulation.py
e = np.hsplit(d, 3) # Split a into 3
print("e = np.hsplit(d, 3) = \n{}\n".format(e))
print("e[1] = \n{}\n".format(e[1]))这段代码输出如下:
e = np.hsplit(d, 3) =
[array([[ 1., 2.],
[ 3., 4.],
[ 5., 6.]]), array([[ 11., 12.],
[ 14., 15.],
[ 17., 18.]]), array([[ 13., 1.],
[ 16., 1.],
[ 19., 1.]])]
e[1] =
[[ 11. 12.]
[ 14. 15.]
[ 17. 18.]]另外,假设我们设置的拆分数量使得原先的数组无法平均拆分,则操作会失败:
# np.hsplit(d, 4) # ValueError: array split does not result in an equal pision
除了指定数量平均拆分,我们也可以指定列数进行拆分。下面是将数组d从第1列和第3列两个地方进行拆分:
# shape_manipulation.py
f = np.hsplit(d, (1, 3)) # # Split a after the 1st and the 3rd column
print("f = np.hsplit(d, (1, 3)) = \n{}\n".format(f))这段代码输出如下。数组d被拆分成了分别包含1,2,3列的三个数组:
f = np.hsplit(d, (1, 3)) =
[array([[ 1.],
[ 3.],
[ 5.]]), array([[ 2., 11.],
[ 4., 14.],
[ 6., 17.]]), array([[ 12., 13., 1.],
[ 15., 16., 1.],
[ 18., 19., 1.]])]最后我们再将数组d在垂直方向进行拆分。同样的,如果指定的拆分数无法平均拆分则会失败:
# shape_manipulation.py
g = np.vsplit(d, 3)
print("np.hsplit(d, 2) = \n{}\n".format(g))
# np.vsplit(d, 2) # ValueError: array split does not result in an equal pision
np.vsplit(d, 3)将产生三个一维数组:
np.vsplit(d, 3) =
[array([[ 1., 2., 11., 12., 13., 1.]]), array([[ 3., 4., 14., 15., 16., 1.]]), array([[ 5., 6., 17., 18., 19., 1.]])]索引
接下来我们看看如何访问NumPy数组中的数据。
同样的,为了测试方便,我们先创建一个一维数组。它的内容是 [100,200)区间的整数。
最基本的,我们可以通过array[index]的方式指定下标来访问数组的元素,这一点对于有一点编程经验的人来说应该都是很熟悉的。
# array_index.py
import numpy as np
base_data = np.arange(100, 200)
print("base_data\n={}\n".format(base_data))
print("base_data[10] = {}\n".format(base_data[10]))上面这段代码输出如下:
base_data =[100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199] base_data[10] = 110
在NumPy中,我们可以创建一个包含了若干个下标的数组来获取目标数组中的元素。如下所示:
# array_index.py
every_five = np.arange(0, 100, 5)
print("base_data[every_five] = \n{}\n".format(
base_data[every_five]))every_five是包含了我们要获取的下标的数组,它的内容大家应该很容易理解。我们可以直接通过方括号的形式来获取到所有我们指定了下标的元素,它们如下:
base_data[every_five] = [100 105 110 115 120 125 130 135 140 145 150 155 160 165 170 175 180 185 190 195]
下标数组可以是一维的,当然也可以是多维的。假设我们要获取一个2X2的矩阵,这个矩阵的内容来自于目标数组中1,2,10,20这四个下标的元素,则可以这样写:
# array_index.py
a = np.array([(1,2), (10,20)])
print("a = \n{}\n".format(a))
print("base_data[a] = \n{}\n".format(base_data[a]))这段代码输出如下:
a = [[ 1 2] [10 20]] base_data[a] = [[101 102] [110 120]]
上面我们看到的是目标数组是一维的情况,下面我们把这个数组转换成一个10X10的二维数组。
# array_index.py
base_data2 = base_data.reshape(10, -1)
print("base_data2 = np.reshape(base_data, (10, -1)) = \n{}\n".format(base_data2))reshape函数前面已经介绍过,大家应该能够想到它的结果:
base_data2 = np.reshape(base_data, (10, -1)) = [[100 101 102 103 104 105 106 107 108 109] [110 111 112 113 114 115 116 117 118 119] [120 121 122 123 124 125 126 127 128 129] [130 131 132 133 134 135 136 137 138 139] [140 141 142 143 144 145 146 147 148 149] [150 151 152 153 154 155 156 157 158 159] [160 161 162 163 164 165 166 167 168 169] [170 171 172 173 174 175 176 177 178 179] [180 181 182 183 184 185 186 187 188 189] [190 191 192 193 194 195 196 197 198 199]]
对于二维数组来说:
假设我们只指定了一个下标,则访问的结果仍然是一个数组。
假设我们指定了两个下标,则访问得到的是其中的元素
我们也可以通过”-1”来指定“最后一个”的元素
# array_index.py
print("base_data2[2] = \n{}\n".format(base_data2[2]))
print("base_data2[2, 3] = \n{}\n".format(base_data2[2, 3]))
print("base_data2[-1, -1] = \n{}\n".format(base_data2[-1, -1]))这段代码输出如下。
对于更高维的数组,原理是一样的,读者可以自行推理。
base_data2[2] = [120 121 122 123 124 125 126 127 128 129] base_data2[2, 3] = 123 base_data2[-1, -1] = 199
除此之外,我们还可以通过”:“的形式来指定范围,例如:2:5 这样。只写”:“则表示全部范围。
请看下面这段代码:
# array_index.py
print("base_data2[2, :]] = \n{}\n".format(base_data2[2, :]))
print("base_data2[:, 3]] = \n{}\n".format(base_data2[:, 3]))
print("base_data2[2:5, 2:4]] = \n{}\n".format(base_data2[2:5, 2:4]))它的含义是:
获取下标为2的行的所有元素
获取下标为3的列的所有元素
获取下标为[2,5)行,下标为[2,4)列的所有元素。请读者仔细观察一下下面的输出结果:
base_data2[2, :]] = [120 121 122 123 124 125 126 127 128 129] base_data2[:, 3]] = [103 113 123 133 143 153 163 173 183 193] base_data2[2:5, 2:4]] = [[122 123] [132 133] [142 143]]
数学运算
NumPy中自然也少不了大量的数学运算函数,下面是一些例子,更多的函数请参见这里NumPy manual contents:
# operation.py
import numpy as np
base_data = (np.random.random((5, 5)) - 0.5) * 100
print("base_data = \n{}\n".format(base_data))
print("np.amin(base_data) = {}".format(np.amin(base_data)))
print("np.amax(base_data) = {}".format(np.amax(base_data)))
print("np.average(base_data) = {}".format(np.average(base_data)))
print("np.sum(base_data) = {}".format(np.sum(base_data)))
print("np.sin(base_data) = \n{}".format(np.sin(base_data)))这段代码输出如下:
base_data = [[ -9.63895991 6.9292461 -2.35654712 -48.45969283 13.56031937] [-39.75875796 -43.21031705 -49.27708561 6.80357128 33.71975059] [ 36.32228175 30.92546582 -41.63728955 28.68799187 6.44818484] [ 7.71568596 43.24884701 -14.90716555 -9.24092252 3.69738718] [-31.90994273 34.06067289 18.47830413 -16.02495202 -44.84625246]] np.amin(base_data) = -49.277085606595726 np.amax(base_data) = 43.24884701268845 np.average(base_data) = -3.22680706079886 np.sum(base_data) = -80.6701765199715 np.sin(base_data) = [[ 0.21254814 0.60204578 -0.70685739 0.9725159 0.8381861 ] [-0.88287359 0.69755541 0.83514527 0.49721505 0.74315189] [-0.98124746 -0.47103234 0.7149727 -0.40196147 0.16425187] [ 0.99045239 -0.66943662 -0.71791164 -0.18282139 -0.5276184 ] [-0.4741657 0.47665553 -0.36278223 0.31170676 -0.76041722]]
矩阵
接下来我们看一下以矩阵的方式使用NumPy。
首先,我们创建一个5X5的随机数整数矩阵。有两种方式可以获得矩阵的转置:通过.T或者transpose函数。另外, 通过dot函数可以进行矩阵的乘法,示例代码如下:
# matrix.py
import numpy as np
base_data = np.floor((np.random.random((5, 5)) - 0.5) * 100)
print("base_data = \n{}\n".format(base_data))
print("base_data.T = \n{}\n".format(base_data.T))
print("base_data.transpose() = \n{}\n".format(base_data.transpose()))
matrix_one = np.ones((5, 5))
print("matrix_one = \n{}\n".format(matrix_one))
minus_one = np.dot(matrix_one, -1)
print("minus_one = \n{}\n".format(minus_one))
print("np.dot(base_data, minus_one) = \n{}\n".format(
np.dot(base_data, minus_one)))
这段代码输出如下:
base_data =
[[-49. -5. 11. -13. -41.]
[ -6. -33. -33. -47. -4.]
[-38. 26. 28. -18. 18.]
[ -3. -19. -15. -39. 45.]
[-43. 6. 18. -15. -21.]]
base_data.T =
[[-49. -6. -38. -3. -43.]
[ -5. -33. 26. -19. 6.]
[ 11. -33. 28. -15. 18.]
[-13. -47. -18. -39. -15.]
[-41. -4. 18. 45. -21.]]
base_data.transpose() =
[[-49. -6. -38. -3. -43.]
[ -5. -33. 26. -19. 6.]
[ 11. -33. 28. -15. 18.]
[-13. -47. -18. -39. -15.]
[-41. -4. 18. 45. -21.]]
matrix_one =
[[ 1. 1. 1. 1. 1.]
[ 1. 1. 1. 1. 1.]
[ 1. 1. 1. 1. 1.]
[ 1. 1. 1. 1. 1.]
[ 1. 1. 1. 1. 1.]]
minus_one =
[[-1. -1. -1. -1. -1.]
[-1. -1. -1. -1. -1.]
[-1. -1. -1. -1. -1.]
[-1. -1. -1. -1. -1.]
[-1. -1. -1. -1. -1.]]
np.dot(base_data, minus_one) =
[[ 97. 97. 97. 97. 97.]
[ 123. 123. 123. 123. 123.]
[ -16. -16. -16. -16. -16.]
[ 31. 31. 31. 31. 31.]
[ 55. 55. 55. 55. 55.]]随机数
本文的最后,我们来看一下随机数的使用。
随机数是我们在编程过程中非常频繁用到的一个功能。例如:生成演示数据,或者将已有的数据顺序随机打乱以便分割出建模数据和验证数据。
numpy.random 包中包含了很多中随机数的算法。下面我们列举四种最常见的用法:
# rand.py
import numpy as np
print("random: {}\n".format(np.random.random(20)));
print("rand: {}\n".format(np.random.rand(3, 4)));
print("randint: {}\n".format(np.random.randint(0, 100, 20)));
print("permutation: {}\n".format(np.random.permutation(np.arange(20))));在四种用法分别是:
生成20个随机数,它们每一个都是[0.0, 1.0)之间
根据指定的shape生成随机数
生成指定范围内([0, 100))的指定数量(20)的随机整数
对已有的数据([0, 1, 2, ..., 19])的顺序随机打乱顺序
这段代码的输出如下所示:
random: [0.62956026 0.56816277 0.30903156 0.50427765 0.92117724 0.43044905 0.54591323 0.47286235 0.93241333 0.32636472 0.14692983 0.02163887 0.85014782 0.20164791 0.76556972 0.15137427 0.14626625 0.60972522 0.2995841 0.27569573] rand: [[0.38629927 0.43779617 0.96276889 0.80018417] [0.67656892 0.97189483 0.13323458 0.90663724] [0.99440473 0.85197677 0.9420241 0.79598706]] randint: [74 65 51 34 22 69 81 36 73 35 98 26 41 84 0 93 41 6 51 55] permutation: [15 3 8 18 14 19 16 1 0 4 10 17 5 2 6 12 9 11 13 7]
相关推荐:
The above is the detailed content of Python machine learning library NumPy. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
1793
16
1735
56
1587
29
267
587
Can a Python class have multiple constructors?
Jul 15, 2025 am 02:54 AM
Yes,aPythonclasscanhavemultipleconstructorsthroughalternativetechniques.1.Usedefaultargumentsinthe__init__methodtoallowflexibleinitializationwithvaryingnumbersofparameters.2.Defineclassmethodsasalternativeconstructorsforclearerandscalableobjectcreati
Accessing data from a web API in Python
Jul 16, 2025 am 04:52 AM
The key to using Python to call WebAPI to obtain data is to master the basic processes and common tools. 1. Using requests to initiate HTTP requests is the most direct way. Use the get method to obtain the response and use json() to parse the data; 2. For APIs that need authentication, you can add tokens or keys through headers; 3. You need to check the response status code, it is recommended to use response.raise_for_status() to automatically handle exceptions; 4. Facing the paging interface, you can request different pages in turn and add delays to avoid frequency limitations; 5. When processing the returned JSON data, you need to extract information according to the structure, and complex data can be converted to Data
Python for loop range
Jul 14, 2025 am 02:47 AM
In Python, using a for loop with the range() function is a common way to control the number of loops. 1. Use when you know the number of loops or need to access elements by index; 2. Range(stop) from 0 to stop-1, range(start,stop) from start to stop-1, range(start,stop) adds step size; 3. Note that range does not contain the end value, and returns iterable objects instead of lists in Python 3; 4. You can convert to a list through list(range()), and use negative step size in reverse order.
python one line if else
Jul 15, 2025 am 01:38 AM
Python's onelineifelse is a ternary operator, written as xifconditionelsey, which is used to simplify simple conditional judgment. It can be used for variable assignment, such as status="adult"ifage>=18else"minor"; it can also be used to directly return results in functions, such as defget_status(age):return"adult"ifage>=18else"minor"; although nested use is supported, such as result="A"i
How to read a JSON file in Python?
Jul 14, 2025 am 02:42 AM
Reading JSON files can be implemented in Python through the json module. The specific steps are: use the open() function to open the file, use json.load() to load the content, and the data will be returned in a dictionary or list form; if you process JSON strings, you should use json.loads(). Common problems include file path errors, incorrect JSON format, encoding problems and data type conversion differences. Pay attention to path accuracy, format legality, encoding settings, and mapping of boolean values and null.
Python for loop to read file line by line
Jul 14, 2025 am 02:47 AM
Using a for loop to read files line by line is an efficient way to process large files. 1. The basic usage is to open the file through withopen() and automatically manage the closing. Combined with forlineinfile to traverse each line. line.strip() can remove line breaks and spaces; 2. If you need to record the line number, you can use enumerate(file, start=1) to let the line number start from 1; 3. When processing non-ASCII files, you should specify encoding parameters such as utf-8 to avoid encoding errors. These methods are concise and practical, and are suitable for most text processing scenarios.
python case-insensitive string compare if
Jul 14, 2025 am 02:53 AM
The most direct way to make case-insensitive string comparisons in Python is to use .lower() or .upper() to compare. For example: str1.lower()==str2.lower() can determine whether it is equal; secondly, for multilingual text, it is recommended to use a more thorough casefold() method, such as "straß".casefold() will be converted to "strasse", while .lower() may retain specific characters; in addition, it should be avoided to use == comparison directly, unless the case is confirmed to be consistent, it is easy to cause logical errors; finally, when processing user input, database or matching
How to use the map function in Python
Jul 15, 2025 am 02:52 AM
Python's map() function implements efficient data conversion by acting as specified functions on each element of the iterable object in turn. 1. Its basic usage is map(function,iterable), which returns a "lazy load" map object, which is often converted to list() to view results; 2. It is often used with lambda, which is suitable for simple logic, such as converting strings to uppercase; 3. It can be passed in multiple iterable objects, provided that the number of function parameters matches, such as calculating the discounted price and discount; 4. Usage techniques include combining built-in functions to quickly type conversion, handling None situations similar to zip(), and avoiding excessive nesting to affect readability. Mastering map() can make the code more concise and professional


