当前位置: 博客首页>> 学习笔记 >> 阅读正文

python学习笔记

作者: 分类: 学习笔记 发布于: 2024-06-14 09:42:09 浏览:1,199 评论(0)


python的基本数据类型

image20240527182535336.png

  • Number 数字

    • 整数:int

    • 浮点数:float

    单斜杠除法: 3/2 = 1.5  结果为浮点数
    双斜杠除法: 3//2 = 1  结果为整型
    
    • bool 布尔
      • 真:True
      • 假:False
    • complex 复数
    16j //j结尾
    
  • str 字符串

    打印原始字符串
    print(r'Hello \n world')
    
  • list 列表

    ['a', 'b']
    
  • tuple 元组

    (1,2,3,4)
    
  • set 集合

    定义:{1,2,3,4}
    差积:{1,2,3,4} - {3,4} 返回 {1,2}
    交积:{1,2,3,4} & {3,4} 返回 {3,4}
    合并:{1,2,3,4} | {2,6} 返回 {1,2,3,4,6}
    定义空集合:  set()
    
  • dict 字典

    {'a': 12, 'b': 21}
    

流程控制语句

  • if elif else

    score = 95
    if score >= 90:
    print('优')
    elif score >= 80:
      print('良')
    elif score >= 70:
      print('中')
    else:
      print('差')
    
  • for

    # list
    words = ['cat', 'window', 'defenestrate']
    for w in words:
        print(w)
    
    # list range
    for i in range(1, 10):
        for j in range(1, i + 1):
            print(i, '*', j, '=', i * j, end=' ')
        print('')
    else:
        print('done')
    
    # dict
    users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}
    for user, status in users.copy().items():
        print(user, status)
    
  • while

    i = 0
    while i <= 100:
        print(i)
        i += 5
    else:
        print('done')
    
    
  • match

    def http_error(status):
        match status:
            case 400:
                return "Bad request"
            case 404:
                return "Not found"
            case 418:
                return "I'm a teapot"
            case _:
                return "Something's wrong with the internet"
    
    
    print(http_error(400))
    

类的定义

# 定义父类
class Human:
    # 类变量
    sum = 0

    # 构造方法
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # 类方法 使用@classmethod 装饰器, 不可访问实例变量,可访问类变量
    @classmethod
    def plus_sum(cls):
        cls.sum += 1

    def get_name(self):
        return self.name

# 定义Student类并继承People
class Student(Human):

    # 构造方法
    def __init__(self, name, age):
        super().__init__(name, age)
        # 私有变量:使用下划线开头,非双下划线结尾的实例变量, 不可在外部设置与访问(python中私有变量是非严格意义上的私有变量, 只不过是换了个参数名, 外部可使用_Student__score读取与设置)
        self.__score = 0

    # 实例方法, 给某人打分
    def marking(self, score):
        if score < 0 or score > 100:
            score = 0
        self.__score = score

    # 实例方法,获取分数
    def get_score(self):
        return self.name + ' score is: ' + str(self.__score)

    # 静态方法 使用@staticmethod 装饰器  不需要指定参数, 不可访问实例变量, 可访问类变量。 方法与类和对象无关时可使用, 不推荐使用
    @staticmethod
    def add(x, y):
        print('this is a static method')

    # 私有方法,外部不可调用. 双下划线开头,非双下划线结尾
    def __private_method(self):
        return self.age


# 实例化
student1 = Student('zhang san', 4)
student1.marking(57)
# 虽然可以强行给此私有参数赋值, 但是此处相当于新增加了一个参数, 与原私有参数无关
# student1.__score = -1

# 打印所有实例变量与值
print(student1.__dict__)

student2 = Student('li si', 19)
# 调用实例方法
print(student1.get_score())

# 外部调用类方法
Student.plus_sum()

# 使用类变量
print('Current student count:' + str(Student.sum))

# 调用静态方法, 可使用实例与类调用
student1.add(1, 2)
Student.add(2, 3)

# 调用父类方法
print(student1.get_name())

正则表达式

import re

# ==============================常量表达式=============================
a = 'C|C++|C#|Javascript|PHP|Python|golang'
c = re.findall('Python', a)
print(c)

# ==============================规则表达式=============================
b = '473tg76g253fr625r46243'
# 找出所有的数字
numbers = re.findall('\\d+', b)
print(numbers)

d = 'C|C++|C#|Javascript|PHP\n|Python|golang'
# 不区分大小写
# re.I 忽略大小写
# re.S  改变.表达式可匹配换行符\n
languages = re.findall('php.', d, re.I | re.S)
print(languages)
# ==============================正则替换=============================
e = '473tg76g253fr625r46243'

# 数字替换成-
r1 = re.sub('\\d', '-', e)
print(r1)

# 数字替换成- 只替换前3个
r2 = re.sub('\\d', '-', e, 3)
print(r2)

# 将php替换成-php-
e2 = 'javaphpgolangpython'


def convert(value):
    matched = value.group()
    return '-' + matched + '-'


r3 = re.sub('php', convert, e2)
print(r3)
# ==============================match 与 search=============================
# match 是从字符串第一个元素开始匹配, 由于第一个不是数字, 所以返回None, 如果找到返回re.Match对象
s = 'F32T23GFG23662R'
s1 = re.match('\\d', s)
print(s1)  # None

# search 尝试搜索字符串, 找到第一个匹配成功的就返回, 返回re.Match对象
s2 = re.search('\\d', s)
print(s2)
# match和search都只匹配一次, 找到匹配结果就返回。 可用于判断字符串是否包含某个表达式的元素

# 尝试获取life和python中间的字符
s3 = 'life is short, i use python'
r3 = re.search('life(.+)python', s3)

# group接收一个参数, 表示取的组里面第几个值
print('r3 group is :', (r3.group(1)))

JSON

import json

# ==============================反序列化=============================
# key:value格式
# json 解析key:value字符串, 得到dict格式
json_str = '{"name": "wayee", "age" : 33}'

# 使用load方法解析json格式, 最终生成 dict 字典格式
me = json.loads(json_str)

print(me, type(me))

# 数组格式
# json 解析数组格式字符串, 得到list格式
json_str1 = '["abc", 3, [], {"age" : 33}]'
arr = json.loads(json_str1)
print(arr)

print(type(arr))  # list

type(arr[3])  # dict

# ==============================序列化=============================
# 字典转字符串
dict = {"name": "wayee", "age": 33, "cool": True}
print(json.dumps(dict))

arr1 = ["name", "wayee", 12, True, False]
print(json.dumps(arr1))

枚举

# 如继承IntEnum表示值只可以是int类型
# from enum import IntEnum
# 使用unique装饰器, 表示值不可以相同
# from enum import unique
from enum import Enum


# @unique
class VIP(Enum):
    YELLOW = 1
    GREEN = 2
    BLACK = 3
    RED = 4


# 打印VIP.YELLOW
print(VIP.YELLOW)

# 打印 YELLOW
print(VIP.YELLOW.name)

# 打印 1
print(VIP.YELLOW.value)

# 枚举转换  打印 VIP.BLACK, 谨用, 不包含时会报错
print(VIP(3))

# 枚举遍历
for v in VIP:
    print(v)

闭包

# 计算总走过的步数
def calculate():
    pos = 0

    def walk(x):
        nonlocal pos
        steps = pos + x
        pos = steps
        return pos

    return walk


f = calculate()
print(f(1))
print(f(3))
print(f(5))
print(f(9))

表达式

# lambda 表达式
f = lambda x, y: x + y
print(f(2, 3))

# 三元表达式
a, b = 3, 6
# x 大于 y 为真是取 x, 否则取 y
r = a if a > b else b

print(r)

# map 与java php javascript的map类似
l = [1, 3, 5, 7, 9]

r1 = map(lambda x: x * x, l)
print(list(r1))

# map 可传入多个列表, 如果个数不同, 结果按最少个数输出结果
l1 = [1, 3, 5, 7]
l2 = [1, 3, 5, 7, 9]

r2 = map(lambda x, y: x * x + y, l1, l2)
print(list(r2))

# reduce

from functools import reduce

l3 = [1, 3, 5, 7, 9]
r3 = reduce(lambda x, y: x + y, l3)

print(r3)

# filter

l4 = [1, 3, 5, 7, 9]
r4 = filter(lambda x: x > 4, l4)
print(list(r4))

       

转载时请注明出处及相应链接。

本文永久链接: http://www.baigei.com/articles/python-study-note