Python学习笔记

2022年05月14日 阅读数:7
这篇文章主要向大家介绍Python学习笔记,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

在这里插入图片描述

1、数据类型和变量

# 1.十六进制表示
if 0x10 == 16:
    print("0x10 == 16") #
else:
    print("0x10 != 16")

# 2.下划线数据表示
if 100_000_000.5 == 100000000.5:
    print("100_000_000.5 == 100000000.5") #
else:
    print("100_000_000.5 != 100000000.5")

# 3.科学计数法
if 1e8 == 100000000:
    print("1e8 == 100000000") #
else:
    print("1e8 != 100000000")

# 4.取消字符串转义
print(r"\n \t \0") # \n \t \0

# 5.布尔值与逻辑运算
print(True and False) # False
print(True or False) # True
print(not False) # True

# 6.空值
if (None == 0):
    print("None == 0")
else:
    print("None != 0") # C中NULL等于0 C++中nullptr也等于0

# 7.Python中的全部变量本质上都是指针
a = ["a"]
b = a # 令b指向a指向的变量
a[0] = "b"
print(b) # ['b']

a = "a"
b = a
a = "b" # a会指向一个新的变量
print(b) # a

# 8.地板除
print(10 // 3) # 3

# 9.Python中的整型能够按照长度动态分配内存 所以理论上没有大小限制
print(10**10000 + 1) # 100···001

2、字符串和编码

#!/usr/bin/env python3
# -*- coding: utf-8 -*-


# 1.字符转换
print(ord("\n")) # 10
print(ord("风")) # 39118
print("\u98ce") # 风 39118D与98ceH相等 \u表示采用Unicode编码

# 2.字符串的编码
print("北京市".encode("utf-8")) # b'\xe5\x8c\x97\xe4\xba\xac\xe5\xb8\x82' bytes
print(b"\xe5\x8c\x97\xe4\xba\xac\xe5\xb8\x82".decode("utf-8")) # 北京市 str
print(len("北京市")) # 3 统计字符数
print(len("北京市".encode("utf-8"))) # 9 统计字节数

# 3.格式化字符串
print("%dD %f %s %xH" % (17, 1.1, "A", 0x11)) # 17D 1.100000 A 11H
print("|%-7.3f|" % (12.34)) # |12.340 | 总共7位 小数点后3位 左对齐

3、数据结构

1.list

list能够由方括号或者list()函数初始化:html

legends = ["Qiyana", "Vi", "Thresh", "Jinx", "Zed"]
print(legends) # ['Qiyana', 'Vi', 'Thresh', 'Jinx', 'Zed']

li = list(range(3))
print(li) # [0, 1, 2]

list的正向索引和反向索引:node

print(legends[0]) # Qiyana
print(legends[1]) # Vi
print(legends[-1]) # Zed
print(legends[-2]) # Jinx

对list中的数据进行增删改查:python

legends.append("Viktor")
print(legends) # ['Qiyana', 'Vi', 'Thresh', 'Jinx', 'Zed', 'Viktor']

legends.insert(1, "Ezreal")
print(legends) # ['Qiyana', 'Ezreal', 'Vi', 'Thresh', 'Jinx', 'Zed', 'Viktor']

legends.pop()
print(legends) # ['Qiyana', 'Ezreal', 'Vi', 'Thresh', 'Jinx', 'Zed']

legends.pop(1)
print(legends) # ['Qiyana', 'Vi', 'Thresh', 'Jinx', 'Zed']

legends.remove("Qiyana")
print(legends) # ['Vi', 'Thresh', 'Jinx', 'Zed']

legends[-2] = "Pyke"
print(legends) # ['Vi', 'Thresh', 'Pyke', 'Zed']

print("Thresh" in legends) # True
print("Ezreal" not in legends) # True

list中的数据类型也能够不一样:web

li = ["A", 1, True, legends]
print(li) # ['A', 1, True, ['Qiyana', 'Vi', 'Thresh', 'Pyke', 'Zed']]
print(li[-1][-1]) # Zed
print(len(li)) # 4

sort()方法能够实现对list的原地排序:正则表达式

li = [2, 4, 6, 5, 3, 1]
li.sort()
print(li) # [1, 2, 3, 4, 5, 6]
li.sort(reverse=True) # 逆序排序
print(li) # [6, 5, 4, 3, 2, 1]

li = ["C", "C++", "Python"]
li.sort(key=len) # 按长排序
print(li) # ['C', 'C++', 'Python']

经过enumerate()函数能够在遍历时跟踪当前序号:编程

li = ["C", "C++", "Python"]
for key, value in enumerate(li):
    print(key, value)
# 0 C
# 1 C++
# 2 Python

2.tuple

tuple自己是一个长度固定、元素不可变的list:json

tup = ("Jinx", "Vi", "Shen") # 括号也可省略
print(tup) # ('Jinx', 'Vi', 'Shen')
print(tup[0]) # Jinx

tup = tuple([1, 2, 3])
print(tup) # (1, 2, 3)

tup = tuple("string")
print(tup) # ('s', 't', 'r', 'i', 'n', 'g')

对于含有单个元素的tuple要经过逗号来消除歧义:数据结构

tup = (1)
print(type(tup)) # <class 'int'>

tup = (1,)
print(type(tup)) # <class 'tuple'>

元素不变指的是元素的指向不变而不是指向的内容不变:app

tup = ("Jinx", ["Vi", "Shen"])
tup[-1][-1] = "Miss Fortune"
print(tup) # 'Jinx', ['Vi', 'Miss Fortune'])

对元组进行运算:dom

tup = (1, True, "str") + (False, "Jinx")
print(tup) # (1, True, 'str', False, 'Jinx')
tup = (1, True, "str") * 3
print(tup) # (1, True, 'str', 1, True, 'str', 1, True, 'str')

若是你想将元组赋值给相似元组的变量,Python会将元组进行拆分:

a, b, (c, d) = (1, 2, (3, 4))
print(a, b, c, d) # 1 2 3 4

利用这个特性能够方便地实现两个变量的交换:

a, b = b, a
print(a, b) # 2 1

变量拆分也能够用来迭代元组或列表序列:

for i, j, k in ((1, 2, 3), (4, 5, 6), (7, 8, 9)):
    print(i, j, k)
# 1 2 3
# 4 5 6
# 7 8 9

count()方法能够用来统计元组中某个值的出现频率:

tup = (1, 0, 0, 8, 6)
print(tup.count(0)) # 2

enumerate()函数能够用于在迭代时追踪元素下标:

li = ["Ezreal", "Neeko", "Thresh"]
for key, value in enumerate(li):
    print(key, value)
# 0 Ezreal
# 1 Neeko
# 2 Thresh  

3.dict

dict的初始化:

dic = {
   
   "C": 1, "C++": 3, "Python": 6}
print(dic) # {'C': 1, 'C++': 3, 'Python': 6}

对dict中的数据进行增删改查

dic["C#"] = 2
print(dic) # {'C': 1, 'C++': 3, 'Python': 6, 'C#': 2}

dic.pop("C++") # dict的pop方法必须传入参数
print(dic) # {'C': 1, 'Python': 6, 'C#': 2}

del dic["Python"]
print(dic) # {'C': 1, 'C#': 2}

dic["C"] = -1
print(dic) # {'C': -1, 'C#': 2}

print(dic["C#"]) # 2

print(dic.get("C")) # -1
print(dic.get("Java")) # None

print("C" in dic) # True
print("Java" in dic) # False

获取字典所有的键和值:

print(dic.keys()) # dict_keys(['C', 'C#'])
print(dic.values()) # dict_values([-1, 2])

4.set

set的初始化:

s = set([1, 2, 3, 2, 3]) # 重复元素在set中会被自动过滤
print(s) # {1, 2, 3}

set的添加和删除:

s.add(4)
print(s) # {1, 2, 3, 4}

s.remove(4)
print(s) # {1, 2, 3}

对set进行集合操做:

s1 = set([1, 2, 3])
s2 = set([2, 3, 4])

print(s1 & s2) # {2, 3}
print(s1.intersection(s2)) # {2, 3}

print(s1 | s2) # {1, 2, 3, 4}
print(s1.union(s2)) # {1, 2, 3, 4}

在这里插入图片描述


4、切片

对list使用切片操做符:

names = ["Sona", "Ezreal", "Vi", "Irelia", "Akali"]
print(names[1:3]) # ['Ezreal', 'Vi'] 左闭右开区间
print(names[:3]) # ['Sona', 'Ezreal', 'Vi'] 从0开始时0能够省略
print(names[1:]) # ['Ezreal', 'Vi', 'Irelia', 'Akali'] 到最后一个截止最后一个也可省略
print(names[-3:-1]) # ['Vi', 'Irelia'] 反向切片
print(names[0:5:2]) # ['Sona', 'Vi', 'Akali'] 改变切片步长

对tuple和字符串使用切片操做符:

print((0, 1, 2, 3, 4)[1:4]) # (1, 2, 3)
print("01234"[1:4]) # 123

5、循环分支

# 1.Python简单循环分支
for i in range(5): # <<=>>
    if i < 2:
        print("<", end="")
    elif i == 2:
        print("=", end="")
    else:
        print(">", end="")
print()

# 2.Python中的for-else结构
for i in range(5):
    pass # 空语句
    # break
else:
    print("The break statement has been executed.") # 当for循环正常执行完毕时else中的语句就会被执行

6、函数

类型转换函数:

print(int("5")) # 5
print(int(5.5)) # 5
print(float("5.5")) # 5.5
print(float(5)) # 5.0
print(str(5)) # 5
print(str(5.5)) # 5.5
print(bool("")) # False
print(bool(1)) # True

Python能够以tuple的形式令一个函数返回多值:

def calculate(a, b):
    return a + b, a - b

addition, subtraction = calculate(1, 2)
print(addition, subtraction) # 3 -1
print(calculate(1, 2)) # (3, -1)

函数能够有一些位置参数(positional)和一些关键字参数(keyword)。关键字参数一般用于指定默认值或可选参数并且关键字参数必须位于位置参数(若是有的话)以后

def sum_(a, b = 1):  # 位置参数在前 关键字参数在后
    return a + b

print(sum_(1)) # 2
print(sum_(1, 2)) # 3

默认参数必须指向不可变对象:

def add_end(l=[]):
    l.append("END")
    return l

print(add_end())  # ['END']
print(add_end())  # ['END', 'END']


def add_end(l=None):
    if l is None:
        l = []
    l.append("END")
    return l

print(add_end())  # ['END']
print(add_end())  # ['END']

可变参数:

def get_sum(*nums):
    total = 0
    for i in nums:
        total += i
    return total

print(get_sum(1, 2, 3))  # 6
print(get_sum(*[1, 2, 3]))  # 6 经过*能够将list或者tuple中的元素做为可变参数传入

关键字参数:

def person(name, age, **kw):
    print(name, age, kw)

person("Ezreal", 20)  # Ezreal 20 {}
person("Ezreal", 20, job="ADC", city="Piltover")  # Ezreal 20 {'job': 'ADC', 'city': 'Piltover'}


def person_(name, age, *, job, city): # 命名关键字参数
    print(name, age, job, city)

person_("Ezreal", 20, job="ADC", city="Piltover")  # Ezreal 20 ADC Piltover

利用递归函数解决汉诺塔问题:

def hanoi(n, a, b, c):
    if n == 1:
        print(a, "->", c, sep="")
    else:
        hanoi(n - 1, a, c, b)
        print(a, "->", c, sep="")
        hanoi(n - 1, b, a, c)

hanoi(3, "a", "b", "c") # a->c a->b c->b a->c b->a b->c a->c

7、迭代

# 1.对dict进行迭代
dict = {
   
   "C": 1, "C++": 3, "Python": 6}
for i in dict:
    print(i) # C C++ Python

for i in dict.values():
    print(i) # 1 3 6

for i in dict.items():
    print(i) # ('C', 1) ('C++', 3) ('Python', 6)

for i, j in dict.items():
    print(i, j) # C 1 C++ 3 Python 6

# 2.判断一个类型是否可迭代
from collections.abc import Iterable

print(isinstance("string", Iterable)) # True
print(isinstance([(1, 2), (3, 4), (5, 6)], Iterable)) # True
print(isinstance(2022, Iterable)) # False

8、列表生成式

# 1.使用列表生成式建立列表
L = list(x * x for x in range(5))
print(L) # [0, 1, 4, 9, 16]

L = list(x for x in range(1, 6) if x % 2 == 0)
print(L) # [2, 4]

L = list(x if x % 2 == 0 else 0 for x in range(1, 6))
print(L) # [0, 2, 0, 4, 0]

# 2.使用列表生成式获取当前目录下的文件和目录名
import os

L = list(i for i in os.listdir("."))
print(L) # ['.DS_Store', 'venv', 'demo.html', 'main.py', '.idea']

9、生成器

一个带有yield的函数就是一个generator,它和普通函数不一样,生成一个generator的过程看起来像是函数调用,但不会执行任何函数代码,直到对其调用next()才开始执行(在 for 循环中会自动调用)。虽然执行流程仍按函数的流程执行,但每执行到一个yield语句就会中断并返回一个迭代值,下次执行时从yield的下一个语句继续执行。

这看起来就好像一个函数在正常执行的过程当中被yield中断了数次,每次中断都会经过yield返回当前的迭代值。

# 1.使用generator生成斐波那契数列
def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1

for i in fib(5):
    print(i) # 1 1 2 3 5

# 2.使用generator生成杨辉三角
def triangles():
    ans = []
    n = 0
    while True:
        line = []
        for i in range(n + 1):
            if i == 0 or i == n:
                line.append(1)
            else:
                line.append(ans[n - 1][i - 1] + ans[n - 1][i])
        yield line
        n = n + 1
        ans.append(line)

n = 0
for i in triangles():
    print(i)
    n = n + 1
    if n == 10:
        break
# [1]
# [1, 1]
# [1, 2, 1]
# [1, 3, 3, 1]
# [1, 4, 6, 4, 1]
# [1, 5, 10, 10, 5, 1]
# [1, 6, 15, 20, 15, 6, 1]
# [1, 7, 21, 35, 35, 21, 7, 1]
# [1, 8, 28, 56, 70, 56, 28, 8, 1]
# [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]

10、高阶函数

# 1.普通高阶函数
def abs_sum(x, y, fun): # 相似于函数指针
    return fun(x) + fun(y)

print(abs_sum(-1, 1, abs)) # 2

# 2.经过map求列表中全部元素的平方
def square(x):
    return x * x

print(list(map(square, [0, 1, 2]))) # [0, 1, 4] map将传入的函数依次做用到序列的每一个元素

# 3.经过reduce将列表转化为整数
from functools import reduce

def add(x, y):
    return x * 10 + y

print(reduce(add, [1, 2, 3])) # 123 reduce把结果继续和序列的下一个元素作累积计算

# 4.经过filter过滤出列表中的全部奇数
def is_odd(x):
    return x % 2 == 1

print(list(filter(is_odd, [1, 2, 3, 4, 5]))) # [1, 3, 5] filter把传入的函数依次做用于每一个元素后根据返回值是True仍是False决定保留仍是丢弃该元素

# 5.经过sorted对列表按绝对值进行逆向排序
print(sorted([1, -2, 3, -4, 5], key=abs, reverse=True)) # [5, -4, 3, -2, 1]

11、匿名函数

# 1.经过匿名函数筛选奇数
print(list(filter(lambda n: n % 2 == 1, range(1, 10))))

12、面向对象编程

# 1.Python简单面向对象
class Legend(object):

    def __init__(self, name, camp):
        self.__name = name # 经过两个下划线将变量变为私有变量
        self.__camp = camp

    def __str__(self):
        return "%s: %s" % (self.__name, self.__camp)

Ezreal = Legend("Ezreal", "Piltover")
print(Ezreal) # Ezreal: Piltover

class MID(Legend): # MID继承自Legend
    pass

Zoe = MID("Zoe", "MountTargon")
print(Zoe) # Zoe: MountTargon

print(type(Ezreal)) # <class '__main__.Legend'>
print(type(Zoe)) # <class '__main__.MID'>
print(isinstance(Zoe, Legend)) # True
print(isinstance(Zoe, MID)) # True

# 2.经过类属性和实例属性统计实例数
class Brand(object):
    count = 0

    def __init__(self, name):
        self.__name = name
        Brand.count = Brand.count + 1

Uni = Brand("Uni")
Sakura = Brand("Sakura")
Pilot = Brand("Pilot")
print(Brand.count) # 3

# 3.经过类实现斐波那契数列
class Fib(object):

    def __init__(self, n):
        self.__a, self.__b = 0, 1
        self.__n = n

    def __iter__(self):
        return self

    def __next__(self):
        self.__a, self.__b = self.__b, self.__a + self.__b
        if self.__a > self.__n:
            raise StopIteration
        return self.__a

for i in Fib(10):
    print(i) # 1 1 2 3 5 8

# 4.枚举类
from enum import Enum

Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
print(Month.Jan.value) # 1
print(Month.Nov.value) # 11

十3、文件操做

# 文件打开
try:
    my_file = open("./main.py", "r")
except FileNotFoundError as e:
    print("FileNotFoundError:", e)
finally:
    pass

# 文件读写
try:
    print(my_file.read())
    my_file.write("#")
except IOError as e:
    print("IOError:", e)
finally:
    pass

# 文件关闭
my_file.close()

在这里插入图片描述


十4、os模块

import os

# 1.获取操做系统信息
print(os.name) # posix
print(os.uname()) # posix.uname_result(sysname='Darwin', nodename='AtreusdeMBP', release='21.4.0', version='Darwin Kernel Version 21.4.0: Fri Mar 18 00:46:32 PDT 2022; root:xnu-8020.101.4~15/RELEASE_ARM64_T6000', machine='arm64')

# 2.操做文件和目录
print(os.path.abspath(".")) # /Users/atreus/PycharmProjects/pythonProject
print(os.path.join("./", "test_dir")) # ./test_dir
os.mkdir("./test_dir") # 建立目录
os.rmdir("./test_dir") # 删除目录

十5、json模块

import json

# 1.使用json对dict进行序列化
languages = {
   
   "C": 1, "C++": 3, "Python": 6}
print(json.dumps(languages)) # {"C": 1, "C++": 3, "Python": 6}

# 2.使用json对list进行序列化
legends = ["Ezreal", "Vi", "Jinx"]
print(json.dumps(legends)) # ["Ezreal", "Vi", "Jinx"]

# 3.使用json进行反序列化
json_str = '{"C": 1, "C++": 3, "Python": 6}'
languages_dict = json.loads(json_str)
print(languages_dict["C++"]) # 3

# 4.使用json对对象进行序列化和反序列化
class Legend(object):

    def __init__(self, name, camp):
        self.name = name
        self.camp = camp

def to_dict(legend):
    return {
   
   
        "name": legend.name,
        "camp": legend.camp
    }

Ezreal = Legend("Ezreal", "Piltover")
print(json.dumps(Ezreal, default=to_dict)) # {"name": "Ezreal", "camp": "Piltover"}

def to_legend(json_dict):
    return Legend(json_dict["name"], json_dict["camp"])

print(json.loads('{"name": "Jinx", "camp": "Zaun"}', object_hook=to_legend)) # <__main__.Legend object at 0x104def100>

十6、正则表达式

import re

# 1.match
print(re.match(r"^\d{3}\-\d{3,8}$", "010-10010")) # <re.Match object; span=(0, 9), match='010-10010'>
print(re.match(r"^\d{3}\-\d{3,8}$", "010 10010")) # None

ans = re.match(r"^(\d{3})\-(\d{3,8})$", "010-10010")
print(ans.group(0)) # 010-10010
print(ans.group(1)) # 010
print(ans.group(2)) # 10010

print(re.match(r"^(\d+)(0*)$", "12300").groups()) # ('12300', '') 贪婪匹配
print(re.match(r"^(\d+?)(0*)$", "12300").groups()) # ('123', '00') 非贪婪匹配

# 2.split
print(re.split(r"\s+", "a b  c   d    e")) # ['a', 'b', 'c', 'd', 'e']

十7、datetime

# 1.datetime
from datetime import datetime

print(datetime.now()) # 2022-05-10 10:16:41.384150
print(datetime(2021, 12, 25, 8, 0)) # 2021-12-25 08:00:00
print(datetime(1970, 1, 1, 8, 0).timestamp()) # 0.0
print(datetime.fromtimestamp(0.0)) # 1970-01-01 08:00:00
print(datetime.now().strftime("%a, %b %d, %H:%M")) # Tue, May 10, 10:24

十8、collections

# 1.namedtuple
from collections import namedtuple

Point = namedtuple("Point", ["x", "y"]) # 将元组定义为一个坐标
point = Point(1, 0)
print(point.x, point.y) # 1 0

Circle = namedtuple("Circle", ["x", "y", "r"]) # 将元组定义为一个圆
circle = Circle(0, 0, 1)
print(circle) # Circle(x=0, y=0, r=1)

# 2.deque
from collections import deque

L = deque([1, 2, 3, 4, 5]) # 双向链表
print(L) # deque([1, 2, 3, 4, 5])
L.append(6)
print(L) # deque([1, 2, 3, 4, 5, 6])
L.appendleft(0)
print(L) # deque([0, 1, 2, 3, 4, 5, 6])
L.pop()
print(L) # deque([0, 1, 2, 3, 4, 5])
L.popleft()
print(L) # deque([1, 2, 3, 4, 5])

# 3.OrderedDict
from collections import OrderedDict

order_dict = OrderedDict([("C", 1), ("C++", 3), ("Python", 6)]) # OrderedDict的Key会按照插入的顺序而不是Key自己排序
print(order_dict) # OrderedDict([('C', 1), ('C++', 3), ('Python', 6)])
print(list(order_dict.keys())) # ['C', 'C++', 'Python']

# 4.Counter
from collections import Counter

counter = Counter()

for i in "Ezreal": # 经过循环更新计数器
    counter[i] += 1
print(counter) # Counter({'E': 1, 'z': 1, 'r': 1, 'e': 1, 'a': 1, 'l': 1})

counter.update("EZ") # 一次性更新计数器
print(counter) # Counter({'E': 2, 'z': 1, 'r': 1, 'e': 1, 'a': 1, 'l': 1, 'Z': 1})

十9、pillow

# 1.利用pillow生成验证码
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random

# 随机字母
def rand_char():
    return chr(random.randint(65, 90))

# 随机颜色
def rand_color():
    return random.randint(64, 255), random.randint(64, 255), random.randint(64, 255)

def back_rand_color():
    return random.randint(32, 127), random.randint(32, 127), random.randint(32, 127)

# 建立Image对象
width = 60 * 4
height = 60
image = Image.new("RGB", (width, height), (255, 255, 255))

# 建立Font对象
font = ImageFont.truetype("Arial.ttf", 36)

# 建立Draw对象
draw = ImageDraw.Draw(image)

# 填充每一个像素
for x in range(width):
    for y in range(height):
        draw.point((x, y), fill=rand_color())

# 输出文字
for t in range(4):
    draw.text((60 * t + 10, 10), rand_char(), font=font, fill=back_rand_color())

# 保存图片
image.save("./code.jpg", "jpeg")

在这里插入图片描述


二10、requests

# 1.经过requests访问网页
import requests
r = requests.get("https://www.liaoxuefeng.com/")
print(r.status_code) # 200
print(r.text[0: 15]) # <!DOCTYPE html>

二11、运算符

在这里插入图片描述