Skip to content
0

文章发布较早,内容可能过时,阅读注意甄别。

Python基础语法

《沁园春·雪》

北国风光注释,千里冰封,万里雪飘。

译文: 北方的风光。

1、python知识

1.1、python保留字

python
import keyword
print(keyword.kwlist)
'''
输出结果:
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
'''
# 单行注释
'''
多行注释
'''
"""
多行注释
"""

1.2、python数据类型

Python3 中常见的数据类型有:

  • Number(数字)
  • String(字符串)
  • bool(布尔类型)
  • List(列表)
  • Tuple(元组)
  • Set(集合)
  • Dictionary(字典)

Python3 的六个标准数据类型中:

  • **不可变数据(3 个):**Number(数字)、String(字符串)、Tuple(元组);
  • **可变数据(3 个):**List(列表)、Dictionary(字典)、Set(集合)。

此外还有一些高级的数据类型,如: 字节数组类型(bytes)。

python
list : [1, 2, 3, 4, 5]
tuple : (1, 2, 3, 4, 5) # 不可变
set : {1, 2, 3, 4, 5}
dictionary: {'张三': 100, '李四': 56, '王五': 79}
python
# 列表生成式
new_lst = [i ** i for i in range(9)]
print(new_lst)
'''
[1, 1, 4, 27, 256, 3125, 46656, 823543, 16777216]
'''
# 元组生成式
new_tuple = (i ** i for i in range(9))
print(new_tuple)
print(tuple(new_tuple))
'''
<generator object <genexpr> at 0x000002E104984900>
(1, 1, 4, 27, 256, 3125, 46656, 823543, 16777216)
'''
# 字典生成式
items = ['Fruits', 'Books', 'Others']
prices = [97, 96, 85]
d = {i: j for i, j in zip(items, prices)}
print(d)
'''
{'Fruits': 97, 'Books': 96, 'Others': 85}
'''
# 集合生成式
new_dic = {i ** i for i in range(9)}
print(new_dic)
'''
{256, 1, 46656, 16777216, 4, 3125, 823543, 27}
'''

1.3、代码举例

1.3.1、数值比较

python
a, b = 10, 10
# a += 1
print('id a', id(a))
print('id b', id(b))
print('value a', a)
print('value b', b)
print(a == b)  # 比的是value
print(a is b)  # 比的是id
'''
id a 140728543161536
id b 140728543161536
value a 10
value b 10
True
True
'''

1.3.2、输入输出

python
num = int(input('请输入一个整数'))
if num % 2:
    print(num, '是奇数')
elif num % 2 == 0:
    print(num, '是偶数')
'''
请输入一个整数:79
79 是奇数
'''

1.3.3、杂

python
print('hello\tWorld')
print(r'hello\tWorld')
print(R'hello\tWorld')
'''
hello	World
hello\tWorld
hello\tWorld
'''

1.4、查看函数的参数和功能

1.4.1、使用dir()函数

dir()是一个内置函数,用于查找对象的所有属性和方法。它返回一个字符串列表,包含了对象的所有属性和方法的名称。

python
import numpy
dir(numpy)
'''
['ALLOW_THREADS',
 'AxisError',
 'BUFSIZE',
 'CLIP',
 'ComplexWarning',
 'DataSource',...
 '''

1.4.2、使用help()函数

Python的内置函数help()可以用于获取函数的帮助信息,包括函数的参数和功能。只需将函数名作为help()的参数即可。

python
import torch
help(torch)
''' (输出)
Help on package torch:

NAME
    torch

DESCRIPTION
    The torch package contains data structures for multi-dimensional
    tensors and defines mathematical operations over these tensors.
    Additionally, it provides many utilities for efficient serialization of
    Tensors and arbitrary types, and other useful utilities.
...
'''

1.4.3、使用__doc__属性

在Python中,每个函数对象都有一个__doc__属性,其中包含了函数的文档字符串。我们可以直接访问这个属性来查看函数的参数和功能。

python
import torch
print(torch.__doc__)
'''输出:
The torch package contains data structures for multi-dimensional
tensors and defines mathematical operations over these tensors.
Additionally, it provides many utilities for efficient serialization of
Tensors and arbitrary types, and other useful utilities.
'''

1.5、python对象

1.5.1、定义对象

python中定义对象使用的是class关键字

1.5.2、__call__方法

在 Python 中,__call__是一个特殊方法(也称为魔术方法或双下划线方法),用于使对象可以像函数一样被调用。当你在一个对象上调用 obj() 时,Python 解释器会查找该对象的__call__方法并调用它

python
class MyClass:
    def __init__(self, value):
        self.value = value

    def __call__(self, x):
        return self.value + x

obj = MyClass(10)
result = obj(5)  # 调用了 __call__ 方法
print(result)  # 输出: 15

在上面的示例中,MyClass 类实现了__call__方法,因此创建的 obj 实例可以像函数一样被调用。在调用 obj(5) 时,实际上会调用 obj.__call__(5),返回的结果是 self.value + x的计算结果,即 10 + 5 = 15__call__方法的灵活性使得对象可以像函数一样被使用,这在某些情况下非常有用,例如实现可调用的对象或者定制对象的行为。

2、anaconda

创建虚拟环境:

bash
conda create -n name python=(版本)

移除虚拟环境:

bash
conda remove -n name --all

3、深度学习

3.1、卷积计算公式

python
torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', device=None, dtype=None)
Hout=Hin+2×padding[0]dilation[0]×(kernel_size[0]1)1stride[0]+1Wout=Win+2×padding[1]dilation[1]×(kernel_size[1]1)1stride[1]+1

3.2、numpy

3.2.1、矩阵运算

  • 当进行向量的内积运算时,可以通过np.dot()

  • 当进行矩阵的乘法运算时,可以通过np.matmul()或者@

  • 当进行标量的乘法运算时,可以通过np.multiply()或者*

python
a = np.arange(1, 11).reshape(2, 5)
b = np.arange(5, 15).reshape(5, 2)
print('a', a)
print('b', b)
print('-----------------------------')
# 矩阵乘法
print('a @ b', a @ b)
print('np.matmul(a, b)', np.matmul(a, b))
print('b @ a', b @ a)
print('np.dot(a, b)', np.dot(a, b))
print('-----------------------------')
# 标量乘法,即各元素相乘
print('b.T', b.T)
print('a * b.T', a * b.T)
a [[ 1  2  3  4  5]
 [ 6  7  8  9 10]]
b [[ 5  6]
 [ 7  8]
 [ 9 10]
 [11 12]
 [13 14]]
-----------------------------
a @ b [[155 170]
 [380 420]]
np.matmul(a, b) [[155 170]
 [380 420]]
b @ a [[ 41  52  63  74  85]
 [ 55  70  85 100 115]
 [ 69  88 107 126 145]
 [ 83 106 129 152 175]
 [ 97 124 151 178 205]]
np.dot(a, b) [[155 170]
 [380 420]]
-----------------------------
b.T [[ 5  7  9 11 13]
 [ 6  8 10 12 14]]
a * b.T [[  5  14  27  44  65]
 [ 36  56  80 108 140]]

3.2.1、维度求和

python
A = np.array([[56.0, 0.0, 4.4, 68.0],
              [1.2, 104.0, 52.0, 8.0],
              [1.8, 135.0, 99.0, 0.9]])
print('A', A.shape, A)
cal_1 = A.sum(axis=0, keepdims=True)
cal_2 = A.sum(axis=1, keepdims=True)
print('cal_1', cal_1.shape, cal_1)
print('cal_2', cal_2.shape, cal_2)
'''
A (3, 4) [[ 56.    0.    4.4  68. ]
		 [  1.2 104.   52.    8. ]
		 [  1.8 135.   99.    0.9]]
cal_1 (1, 4) [[ 59.  239.  155.4  76.9]]
cal_2 (3, 1) [[128.4]
			 [165.2]
			 [236.7]]
'''

TIP

WARNING

NOTE

CAUTION

最近更新