再梳理一遍 Python 系列知识点,夯实基础,无他,唯手熟尔

Python 系列总结都是我自己平时的学习笔记,如果有不正确的地方,希望各位佬儿哥指正纠偏🤗

常用模块-math

import math

常用模块-random

import random

常用模块-json

import json

d = {'name':'Tom','age':26}
j = json.dumps(d)
d2 = json.loads(j)

print(d)
print(type(d))
print()
print(j)
print(type(j))
print()
print(d2)
print(type(d2))
-------------------------------------
{'name': 'Tom', 'age': 26}
<class 'dict'>

{"name": "Tom", "age": 26}
<class 'str'>

{'name': 'Tom', 'age': 26}
<class 'dict'>

常用模块-time

import time

n = time.time()
print(n)
n1 = round(n,3)
print(n1)
------------------------
1675392067.2974966
1675392067.297

常用模块-datetime()

import datetime

dt = datetime.datetime.now()

print(dt)
print('dt.year:' + str(dt.year) + '---type:' + str(type(dt.year)))
print('dt.month:' + str(dt.month) + '---type:' + str(type(dt.month)))
print('dt.day:' + str(dt.day) + '---type:' + str(type(dt.day)))
print('dt.hour:' + str(dt.hour) + '---type:' + str(type(dt.hour)))
print('dt.minute:' + str(dt.minute) + '---type:' + str(type(dt.minute)))
print('dt.second:' + str(dt.second) + '---type:' + str(type(dt.second)))
----------------------------------------------------------------------------------------------------------
2023-02-03 11:00:08.205691
dt.year:2023---type:<class 'int'>
dt.month:2---type:<class 'int'>
dt.day:3---type:<class 'int'>
dt.hour:11---type:<class 'int'>
dt.minute:0---type:<class 'int'>
dt.second:8---type:<class 'int'>
import datetime
import time

now = time.time()
date = datetime.datetime.fromtimestamp(now)

print(now)
print(date)
----------------------------------------------------------------------------
1675393953.0860312
2023-02-03 11:12:33.086031
import datetime
import time

d1 = datetime.datetime.now()
time.sleep(1)
d2 = datetime.datetime.now()

print(d2>d1)
-----------------------------------------------
True
import datetime
import time

d1 = datetime.datetime.now()
time.sleep(1)
d2 = datetime.datetime.now()
d3 = d2 -d1

print(d3)
print(type(d3))
------------------------------------------------
0:00:01.002022
<class 'datetime.timedelta'>
import datetime

dt = datetime.timedelta(days=11,hours=10,minutes=9,seconds=8)

print(dt)
print(type(dt))
print(dt.days)
print(dt.seconds) # 天不参与计算,10*60*60 + 9*60 + 8 = 36548
print(dt.total_seconds()) # 11*24*60*60 + 10*60*60 + 9*60 + 8 = 986948
print(str(dt))
---------------------------------------------------------------------------------------------------------
11 days, 10:09:08
<class 'datetime.timedelta'>
11
36548
986948.0
11 days, 10:09:08
import datetime

dt = datetime.datetime.now()
print(dt)

thounsandDays = datetime.timedelta(days=1000)
print(thounsandDays)

print(dt + thounsandDays)
------------------------------------------------------------------------------
2023-02-06 14:20:46.265084
1000 days, 0:00:00
2025-11-02 14:20:46.265084

常用模块-logging

Logging 库是非常常用的记录日志库,通过 logging 模块存储各种格式的日志,主要用于输出运行日志,可以设置输出日志的等级、日志保存路径、日志文件回滚等;

import logging

logging.basicConfig(format='%(levelname)s %(asctime)s: %(message)s: %(module)s',level=logging.DEBUG)
logging.debug('This message should appear on the console')
logging.info('So should this')
logging.warning('And this, too')
-----------------------------------------------------------------------------------------------------
DEBUG 2023-02-07 17:04:37,473: This message should appear on the console: logging_practice
INFO 2023-02-07 17:04:37,473: So should this: logging_practice
WARNING 2023-02-07 17:04:37,473: And this, too: logging_practice
import logging

logging.basicConfig(filename='myProgramLog',format='%(levelname)s %(asctime)s: %(message)s: %(module)s',level=logging.DEBUG)
logging.debug('This message should appear on the console')
logging.info('So should this')
logging.warning('And this, too')
import logging

logging.disable(logging.CRITICAL)

logging.basicConfig(filename='myProgramLog',format='%(levelname)s %(asctime)s: %(message)s: %(module)s',level=logging.DEBUG)
logging.debug('This message should appear on the console')
logging.info('So should this')
logging.warning('And this, too')

常用模块-threading

import time
import threading

print('Start of program.')

def takeANap():
    time.sleep(5)
    print('Wake up!')

threadObj = threading.Thread(target=takeANap)
threadObj.start()
print('End of program')
----------------------------------------------------------------------------
Start of program.
End of program
Wake up!

注意:target 参数名后传的是方法名,不加 (),因为此处并不是调用。

import threading

l = [1,2,3,4]

def a(*args):
    for _ in args:
        print(_)

thread_a = threading.Thread(target=a,args=l)
thread_a.start()
------------------------------------------------------------------------
1
2
3
4
import threading

d = {'name': 'Tom', 'age': 18}

def b(**kwargs):
    for k, v in kwargs.items():
        print(str(k) + ':' + str(v))

thread_b = threading.Thread(target=b, kwargs=d)
thread_b.start()
----------------------------------------------------------------------------
name:Tom
age:18
# 不使用join,两个线程并行运行
import time
import threading

def a():
    time.sleep(1)
    print('我是a:1/3')
    time.sleep(1)
    print('我是a:2/3')
    time.sleep(1)
    print('我是a:3/3')

def b():
    print('我是b:1/2')
    print('我是b:2/2')

thread_a = threading.Thread(target=a)
thread_b = threading.Thread(target=b)

thread_a.start()
thread_b.start()
-------------------------------------------------------------
我是b1/2
我是b2/2
我是a1/3
我是a2/3
我是a3/3
# 使用join,线程b需要等线程a运行完后再运行
import time
import threading

def a():
    time.sleep(1)
    print('我是a:1/3')
    time.sleep(1)
    print('我是a:2/3')
    time.sleep(1)
    print('我是a:3/3')

def b():
    print('我是b:1/2')
    print('我是b:2/2')

thread_a = threading.Thread(target=a)
thread_b = threading.Thread(target=b)

thread_a.start()
thread_a.join()
thread_b.start()
--------------------------------------------------------------
我是a1/3
我是a2/3
我是a3/3
我是b1/2
我是b2/2
# join()方法可以自定义timeout参数,意为最长暂用CPU时间,如果不设置的话就永远等待;
import time
import threading

def a():
    time.sleep(1)
    print('我是a:1/3')
    time.sleep(1)
    print('我是a:2/3')
    time.sleep(1)
    print('我是a:3/3')

def b():
    print('我是b:1/2')
    print('我是b:2/2')

thread_a = threading.Thread(target=a)
thread_b = threading.Thread(target=b)

thread_a.start()
thread_a.join(timeout=2)
thread_b.start()
-------------------------------------------------------------
我是a1/3
我是a2/3
我是b1/2
我是b2/2
我是a3/3

深拷贝浅拷贝

不可变数据类型(如整型,字符串等)在 Python 中只是拷贝了值,因此在执行浅拷贝时实际上是创建了一个新的副本,而不是拷贝引用。因此,对原数据的更改不会影响到拷贝后的数据。

import copy

a = 1000
b = a
c = copy.copy(a)
d = copy.deepcopy(a)

print(a, b, c, d)
print(id(a), id(b), id(c), id(d))

a += 1

print(a, b, c, d)
print(id(a), id(b), id(c), id(d))

----------------------------------------------
1000 1000 1000 1000
2518799374640 2518799374640 2518799374640 2518799374640
1001 1000 1000 1000
2518805613936 2518799374640 2518799374640 2518799374640

对于可变数据类型,浅拷贝只拷贝第一层中的引用,深拷贝在拷贝时,会逐层进行拷贝,直到所有的引用都是不可变对象为止。

import copy

a = [1, 2, [3, 4]]
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
e = a.copy()
f = a[:]

print(a, b, c, d, e,f)
print(id(a), id(b), id(c), id(d), id(e),id(f))
print()

a.append(5)

print(a, b, c, d, e,f)
print(id(a), id(b), id(c), id(d), id(e),id(f))
print()

a[2].append(6)
print(a, b, c, d, e,f)
print(id(a), id(b), id(c), id(d), id(e),id(f))
----------------------------------------------------
[1, 2, [3, 4]] [1, 2, [3, 4]] [1, 2, [3, 4]] [1, 2, [3, 4]] [1, 2, [3, 4]] [1, 2, [3, 4]]
2213595331584 2213595331584 2213595362304 2213595356992 2213595443008 2213595442368

[1, 2, [3, 4], 5] [1, 2, [3, 4], 5] [1, 2, [3, 4]] [1, 2, [3, 4]] [1, 2, [3, 4]] [1, 2, [3, 4]]
2213595331584 2213595331584 2213595362304 2213595356992 2213595443008 2213595442368

[1, 2, [3, 4, 6], 5] [1, 2, [3, 4, 6], 5] [1, 2, [3, 4, 6]] [1, 2, [3, 4]] [1, 2, [3, 4, 6]] [1, 2, [3, 4, 6]]
2213595331584 2213595331584 2213595362304 2213595356992 2213595443008 2213595442368

对象的可哈希性

注意:只有可哈希对象才能被放进集合或者作为字典的键

sorted() 函数

sorted 函数是 Python 内置函数,用于对可迭代对象进行排序,并返回一个新的列表。
注意:sorted 函数不会改变原来的可迭代对象,而是返回一个新的列表。如果需要改变原来的可迭代对象,可以使用 sort 方法,但它只能用于列表。
参数:

enumerate() 函数

enumerate() 适用于任何"可迭代对象",可以用于列表、元祖、字典、字符串等。

def enumerate_func():
    names = ['lily','wenwen','tom']
    for index, s in enumerate(names,start=1):
        print(index,s)
---------------------------------------------
1 lily
2 wenwen
3 tom

如果不指定 start 参数,则 index 从 0 开始

测试基础-Python 篇 基础③


↙↙↙阅读原文可查看相关链接,并与作者交流