目录

莫烦Python基础笔记部分

莫烦Python基础笔记(部分)

课程链接

【【莫烦Python】Python 基础教程】

快速回顾一下语法,把一些容易忘的记下来

函数定义

注意:函数参数带默认值时,所有带默认值的参数要靠右

"""
莫凡 python教程
"""

def fun(a, b):
    return a * 3 + b

# 参数带默认值
def fun2(a, b=1):
    return a * b


print(fun(1, 2))
# 可以在传递参数的过程中,用=指定每个形参对应的值
print(fun(b=1, a=2))

类的属性可以直接用[self.]来访问。

class Calculator:
    # def __init__(self):
    #     self.y = None
    #     self.x = None

    def load(self, x, y):
        self.x = x
        self.y = y

cal = Calculator()
cal.load(2,3)
print(cal.x)

列表

a = [1, 2, 3, 4, 5, 6, 7]

# 负数索引表示倒着数
# 倒数第一个
print(a[-1])  # 7
print(a[-2])  # 6
print(a[-3:-1])  # [5, 6]

# 返回某元素第一次出现的索引
print(a.index(2))  # 1

字典

def fun():
    pass
# 值可以是列表,函数,字典
# 键必须是不可变的,不能是列表
d = {1: 'app', 2: [1, 2, 3], 3: fun}

print(d)
del d[3]  # 删除键值对
print(d)

# {1: 'app', 2: [1, 2, 3], 3: <function fun at 0x00000274790F7E18>}
# {1: 'app', 2: [1, 2, 3]}

import引入模块

最基础的全部引入

# as起别名
import time as t

# print(time.localtime())
print(t.localtime())

部分引入

# 部分引入
from time import time,localtime
# 不需要再加上time.
print(time())
print(localtime())

用*快捷全部引入

from time import *
print(time())

引入自定义的模块

在同一目录下,直接使用文件名即可引入

from classBasic import Calculator
from gloal_variable import fun
fun(1,2)
cal = Calculator()

错误处理

try:
    file = open('try', 'r')
except Exception as e:
    print(e)  # [Errno 2] No such file or directory: 'try'
else:
    pass #try中的语句没有丢出错误

zip,lambda和map

# zip,将每个列表的元素依次打包成元组
a = [1, 2, 3]
b = ['a', 'b', 'c', 'd']
print(list(zip(a, b)))  # 以短的为准,[(1, 'a'), (2, 'b'), (3, 'c')]

# lambda
fun2 = lambda x, y: x + y
print(fun2(1, 2))

# map
print(list(map(fun2, [2], [1, 2])))  # [3]
print(list(map(fun2, [2, 2], [1, 2])))  # [3, 4]

拷贝模块copy

import copy

a = [1, 2, [3, 4]]
b = a
print(id(a))  # id获得唯一的索引
print(id(b))
c = copy.deepcopy(a)  # 深拷贝
print(id(c))
d = copy.copy(a)
print(id(d))

d[0] = 22
c[1] = 12
print(a)
print(d)
print(c)

print(id(a[2]) == id(c[2]))
print(id(a[2]) == id(d[2]))

# 2762199305536
# 2762199305536
# 2762199305024
# 2762199304768
# [1, 2, [3, 4]]
# [22, 2, [3, 4]]
# [1, 12, [3, 4]]
# False
# True

pickle存取数据

backbone_name = 'resnet'
layers_to_extract_from = ['layer_2', 'layer_3']

dict_1 = {
    1: 'a',
    "backbone.name": backbone_name,
    "layers_to_extract_from": layers_to_extract_from,
}
# 可以保存一些数据,比如字典
with open('pickle_example', 'wb') as f:  # with语句包裹可以自动关闭文件
    pickle.dump(dict_1, f)

with open('pickle_example', 'rb') as f:
    dict_2 = pickle.load(f)
print(dict_2)  #  {1: 'a', 'backbone.name': 'resnet', 'layers_to_extract_from': ['layer_2', 'layer_3']}

结语

p31之后的部分不做笔记了