python零碎知识点
集合只保留第一个元素
-
使用
next
和iter
函数:pythonCopy codes = {1, 2, 3, 4} s = {next(iter(s))}
-
转换为列表并选择第一个元素:
pythonCopy codes = {1, 2, 3, 4} s = {list(s)[0]}
-
使用
pop
方法移除其它元素:pythonCopy codes = {1, 2, 3, 4} first_element = next(iter(s)) s.clear() s.add(first_element)
DataFrame转换成列表套字典
要将DataFrame中的两列转换成列表套字典的格式,我们可以使用to_dict
方法,并指定orient='records'
。这里假设DataFrame的两列分别是“序号”和“提示词”,可以使用以下代码来完成转换:
pythonCopy codeimport pandas as pd
# 假设这是你的DataFrame
data = {
'序号': [1, 2, 3],
'提示词': ['apple', 'banana', 'cherry']
}
df = pd.DataFrame(data)
# 转换DataFrame到列表套字典
result = df.rename(columns={'序号': 'id', '提示词': 'title'}).to_dict(orient='records')
print(result)
DPI获取
1. 在Python中获取显示器DPI
如果您使用的是Windows系统,可以使用win32api
模块来获取屏幕的DPI。以下是一个例子:
pythonCopy codeimport ctypes
def get_screen_dpi():
# 创建一个DC(Device Context)对象,用于后续获取DPI
user32 = ctypes.windll.user32
dc = user32.GetDC(0)
# DPI for X Axis and Y Axis (usually the same for modern screens)
dpi_x = ctypes.windll.gdi32.GetDeviceCaps(dc, 88) # 88 is the index for LOGPIXELSX
dpi_y = ctypes.windll.gdi32.GetDeviceCaps(dc, 90) # 90 is the index for LOGPIXELSY
user32.ReleaseDC(0, dc)
return dpi_x, dpi_y
dpi_x, dpi_y = get_screen_dpi()
print(f"The screen DPI is {dpi_x} by {dpi_y}")
2. 在Web浏览器中估算DPI
如果您正在开发一个Web应用,可以使用JavaScript来估算浏览器的DPI:
javascriptCopy codefunction getDPI() {
var div = document.createElement("div");
div.style.height = "1in";
div.style.width = "1in";
div.style.top = "-100%";
div.style.left = "-100%";
div.style.position = "absolute";
document.body.appendChild(div);
var dpi = window.getComputedStyle(div).getPropertyValue('width');
document.body.removeChild(div);
return parseFloat(dpi);
}
console.log("The DPI of this screen is", getDPI());
3. 使用Pillow获取和设置图像DPI
如果您在处理图像,并需要获取或设置图像的DPI,可以使用Pillow库:
pythonCopy codefrom PIL import Image
image_path = 'path_to_your_image.jpg'
img = Image.open(image_path)
dpi = img.info.get('dpi')
if dpi:
print("DPI of the image:", dpi)
else:
print("DPI information is not available.")
# 设置DPI
img.save('output.jpg', dpi=(300, 300))
4. 通过操作系统的设置
在Linux或Mac OS中,您可以通常通过系统设置或使用系统命令行工具来查看或修改DPI设置。
深拷贝
直接使用 copy.deepcopy()
import copy
slide_layout_json = {
"id": f"page_{j + 1}",
"elements": [],
"background": {
"type": "image",
"image": image_path
},
}
# 使用 deepcopy 来深拷贝 slide_layout_json
slide_layout_total_json = copy.deepcopy(slide_layout_json)
License:
CC BY 4.0