Eastsheng's Wiki

Python奇淫巧计-2

2023-03-16 10:48:28

[toc]

修改jupyter lab默认浏览器

  • 设置Windows chrome浏览器软链至wsl2 ubuntu

    1
    sudo ln -sf /mnt/d/softwares/Google/Chrome/Application/chrome.exe /usr/bin/chrome
    • 输入chrome测试是否能打开浏览器
  • 生成jupyter_lab_config.py

    1
    jupyter lab --generate-config
  • 将下面代码粘贴至:jupyter_lab_config.py

    1
    2
    3
    4
    import webbrowser
    webbrowser.register('chrome',None,webbrowser.GenericBrowser('/usr/bin/chrome'))
    c.NotebookApp.browser = 'chrome'
    c.NotebookApp.use_redirect_file = False

寻找并拟合峰

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import numpy as np
from scipy.signal import find_peaks
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# 以下函数不保证正确,只看方法
# 定义洛伦兹函数
def lorentz_func(x, a, b, c):
return a / (1 + ((x-b)/c)**2)

x = np.linspace(0, 10, 1000)
y = np.sin(x) + 0.5 * np.sin(3*x) + 0.2 * np.sin(5*x)

peaks, _ = find_peaks(y)

peak_positions = x[peaks]

# 对每个峰进行拟合
peak_params = []
for peak_pos in peak_positions:
# 提取拟合区域
x_fit = x[(x > peak_pos - 0.1) & (x < peak_pos + 0.1)]
y_fit = y[(x > peak_pos - 0.1) & (x < peak_pos + 0.1)]
# print(x_fit,y_fit)
# 进行拟合
init_params = [y_fit.max(), peak_pos, 0.01] # 初始拟合参数,可根据实际情况修改
# print(init_params)
try:
params, _ = curve_fit(lorentz_func, x_fit, y_fit, p0=init_params)
peak_params.append(params)
except RuntimeError:
# 如果拟合失败则跳过
print("pass")
pass
# 提取每个峰的弛豫时间
fre = [params[1] for params in peak_params]
relax_times = [1/(2*params[2]) for params in peak_params]
print(fre,relax_times)
plt.plot(x, y)
plt.plot(x[peaks], y[peaks], "x")
plt.show()

文件判断

判断某个文件夹是否存在

1
2
3
4
5
6
import os

if os.path.exists('文件路径'):
print('文件夹存在')
else:
print('文件夹不存在')

判断某个文件是否存在

1
2
3
4
5
6
7
8
import os

filename = "example.txt"

if os.path.isfile(filename):
print("文件存在")
else:
print("文件不存在")

列表解析式(List comprehension)实现矩阵转置

1
2
3
4
5
6
7
8
9
10
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transpose = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
print(matrix)
print(transpose)

"""
out
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
"""

同时遍历两个序列

1
2
3
4
5
6
7
8
9
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for i, (name, age) in enumerate(zip(names, ages)):
print(i, name, age)
"""
0 Alice 25
1 Bob 30
2 Charlie 35
"""

Python 的装饰器(Decorator)实现函数运行时间的计算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import time

def timing_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Function {func.__name__} took {end_time - start_time} seconds to run.")
return result
return wrapper

@timing_decorator
def my_function():
# some code here
for i in range(1100):
print("hello python!")
return


if __name__ == '__main__':
my_function()