【Python】基础学习技能提升代码样例2:小功能块

配合以前两篇文章使用:
python易忘操作和小知识点集锦
常用算法模板与知识点

使用 Python 3.x

一、小功能

# 把数字转换为货币字符串
import locale
# Set the locale to United States
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
# Example number
amount = 1234567.89
# Format as currency string
formatted_amount = locale.currency(amount, grouping=True)
# Display the formatted currency string
print(f'Formatted Amount: {formatted_amount}')# 生成随机字符串
import random
import string
def generate_random_string(length):characters = string.ascii_letters + string.digitsrandom_string = ''.join(random.choice(characters) for _ in range(length))return random_string
# Generate a random string of length 8
random_string = generate_random_string(8)
# Display the random string
print(f'Random String: {random_string}')# Base64编码字符串
import base64
# Original string
original_string = 'Hello, 你好!'
# Encode the string to Base64
base64_encoded_string = base64.b64encode(original_string.encode('utf-8')).decode('utf-8')
# Display the result
print(f'Original String: {original_string}')
print(f'Base64 Encoded String: {base64_encoded_string}')# 格式化时间
from datetime import datetime
# Get the current date
current_date = datetime.utcnow()
# Format the date
formatted_date = current_date.strftime('%A, %B %d, %Y')
# Display the result
print(f'Formatted Date: {formatted_date}')
# 显示当前时间
# Get the current date
current_date = datetime.now()
# Format the current date as a string
formatted_date = current_date.strftime('%m/%d/%Y')  # Adjust the format as needed
# Display the result
print(f'Current Date: {formatted_date}')
# 比较两个时间
# Example dates
date1 = datetime.strptime('2022-01-01', '%Y-%m-%d')
date2 = datetime.strptime('2023-01-01', '%Y-%m-%d')
# Compare dates
if date1 < date2:print(f'{date1} is earlier than {date2}')
elif date1 > date2:print(f'{date1} is later than {date2}')
else:print(f'{date1} is equal to {date2}')
# 获取时间戳
current_date = datetime.now()
numeric_date = int(current_date.timestamp() * 1000) # 毫秒时间戳# 从数组中移除值
# Example list
original_list = [1, 2, 3, 4, 5]
item_to_remove = 3
# Find the index of the item to remove
try:index_to_remove = original_list.index(item_to_remove)# Remove the item from the listoriginal_list.pop(index_to_remove)print('Original List:', original_list)
except ValueError:print('Item not found in the list.')# 从数组中随机取值
import random
# Example list
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Get a random item from the list
random_item = random.choice(my_list)
# Display the result
print('Random Item:', random_item)# 数组求交集
# Example lists
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
# Find the intersection
intersection = [value for value in list1 if value in list2]# 数组分块
def chunk_array(array, chunk_size):result = []for i in range(0, len(array), chunk_size):result.append(array[i:i+chunk_size])return result
# Example array
my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Split the array into chunks of size 3
chunks = chunk_array(my_array, 3)
# Display the result
print('Original Array:', my_array)
print('Chunks:', chunks)# 获取文件后缀
def get_file_extension(file_name):# Split the file name based on the dotparts = file_name.split('.')# Get the last part of the array (the file extension)extension = parts[-1]return extension
# Example usage
file_name = 'example.txt'
file_extension = get_file_extension(file_name)
print(f'File Extension: {file_extension}')# 判断邮箱是否合规
import re
def validate_email(email):# Regular expression for a basic email validationemail_regex = r'^[^\s@]+@[^\s@]+\.[^\s@]+$'# Test the email against the regular expressionreturn re.match(email_regex, email) is not None
# Example usage:
email_to_validate = 'example@email.com'
if validate_email(email_to_validate):print('Email is valid')
else:print('Email is not valid')# 一定时延后执行某函数
import threading
def my_function(parameter):print('Parameter received:', parameter)
# Define the parameter
my_parameter = 'Hello, world!'
# Define a function to be executed after a delay
def delayed_execution():my_function(my_parameter)
# Schedule the function to be executed after a delay
timer = threading.Timer(1.0, delayed_execution)
timer.start()# 函数重载(overloadding)
def example_function(*args):if len(args) == 0:# No arguments providedprint('No arguments')elif len(args) == 1 and isinstance(args[0], int):# One argument of type number providedprint('One number argument:', args[0])elif len(args) == 2 and isinstance(args[0], str) and isinstance(args[1], int):# Two arguments: a string followed by a numberprint('String and number arguments:', args[0], args[1])else:# Default caseprint('Invalid arguments')
# Example usage
example_function()
example_function(42)
example_function('Hello', 7)
example_function(True, 'world')  # Invalid arguments# 栈(Stack)构造,FILO
class Stack:def __init__(self):self.items = []# Push an element onto the stackdef push(self, element):self.items.append(element)# Pop the top element from the stackdef pop(self):if self.is_empty():return 'Underflow'return self.items.pop()# Peek at the top element without removing itdef peek(self):return self.items[-1] if self.items else None# Check if the stack is emptydef is_empty(self):return len(self.items) == 0# Get the size of the stackdef size(self):return len(self.items)# Print the stack elementsdef print(self):print(self.items)
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print('Stack elements:')
stack.print()  # Outputs: [1, 2, 3]
print('Top element:', stack.peek())  # Outputs: 3
print('Popped element:', stack.pop())  # Outputs: 3
print('Stack size:', stack.size())  # Outputs: 2
print('Is the stack empty?', stack.is_empty())  # Outputs: False# 构建队列(Queue) FIFO
class Queue:def __init__(self):self.items = []# Enqueue an element at the end of the queuedef enqueue(self, element):self.items.append(element)# Dequeue the element from the front of the queuedef dequeue(self):if self.is_empty():return 'Underflow'return self.items.pop(0)# Peek at the front element without removing itdef front(self):if self.is_empty():return 'Queue is empty'return self.items[0]# Check if the queue is emptydef is_empty(self):return len(self.items) == 0# Get the size of the queuedef size(self):return len(self.items)# Print the queue elementsdef print(self):print(self.items)
# Example usage
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print('Queue elements:')
queue.print()  # Outputs: [1, 2, 3]
print('Front element:', queue.front())  # Outputs: 1
print('Dequeued element:', queue.dequeue())  # Outputs: 1
print('Queue size:', queue.size())  # Outputs: 2
print('Is the queue empty?', queue.is_empty())  # Outputs: False# 获取图片尺寸
from PIL import Image
import requests
from io import BytesIO
def get_image_dimensions(image_url):try:# Make a request to get the image contentresponse = requests.get(image_url)# Open the image using PILimg = Image.open(BytesIO(response.content))# Get the dimensionswidth, height = img.size# Display the dimensionsprint('Width:', width)print('Height:', height)except Exception as e:print('Error loading the image:', e)
# Example usage
image_url = 'path/to/your/image.jpg'
get_image_dimensions(image_url)# 获取随机颜色
import random
def generate_random_color():# Generate random values for red, green, and blue componentsred = random.randint(0, 255)green = random.randint(0, 255)blue = random.randint(0, 255)# Create the RGB color stringcolor = f'rgb({red}, {green}, {blue})'return color
# Example usage:
random_color = generate_random_color()
print('Random Color:', random_color)# 随机密码生成
import random
import string
def generate_random_password(length):# Define character setsuppercase_chars = string.ascii_uppercaselowercase_chars = string.ascii_lowercasenumeric_chars = string.digitsspecial_chars = '!@#$%^&*()-_+='# Combine character setsall_chars = uppercase_chars + lowercase_chars + numeric_chars + special_chars# Check if the input length is a valid positive numberif not isinstance(length, int) or length <= 0:return 'Invalid input. Please provide a positive integer for the password length.'# Generate the random passwordpassword = ''.join(random.choice(all_chars) for _ in range(length))return password
# Example usage:
password_length = 12
random_password = generate_random_password(password_length)
print(f'Generated Password: {random_password}')# 二进制字符串转换为数字
def binary_to_decimal(binary_string):# Check if the input is a valid binary stringif not all(char in '01' for char in binary_string):return 'Invalid input. Please provide a valid binary string.'# Convert binary to decimaldecimal_value = int(binary_string, 2)return decimal_value
# Example usage:
binary_number = '1101'
decimal_result = binary_to_decimal(binary_number)
print(f'The decimal equivalent of binary {binary_number} is {decimal_result}')# 对象转换成json字符串
import json
# Example dictionary representing the object
person = {'firstName': 'John','lastName': 'Doe','age': 30
}
# Convert dictionary to a JSON-formatted string
json_string = json.dumps(person)
# Display the result
print('Original Dictionary:')
print(person)
print('\nJSON-formatted String:')
print(json_string)# RGB 转 HEX
def convert_to_hex(red, green, blue):def to_hex(value):hex_value = format(value, '02x')return hex_valuehex_red = to_hex(red)hex_green = to_hex(green)hex_blue = to_hex(blue)return f'#{hex_red}{hex_green}{hex_blue}'
# Example usage
red_value = int(input('Enter the Red value (0-255): '))
green_value = int(input('Enter the Green value (0-255): '))
blue_value = int(input('Enter the Blue value (0-255): '))
hex_result = convert_to_hex(red_value, green_value, blue_value)
print(f'HEX: {hex_result}')# url解析 或者用 urllib.parse
import re
def break_url(url):url_parts = {}url_regex = r'^(\w+):\/\/([\w.-]+)(\/.*)?$'matches = re.match(url_regex, url)if not matches:print('Invalid URL format.')returnurl_parts['scheme'] = matches.group(1)url_parts['domain'] = matches.group(2)url_parts['path'] = matches.group(3) or ''print('URL Parts:')print(url_parts)
# Example: Breakdown the URL 'https://www.example.org/page'
break_url('https://www.example.org/page')# 替换路径中的..和.
def simplify_absolute_path(path):parts = path.split('/')simplified_parts = []for part in parts:if part == '..':if simplified_parts:simplified_parts.pop()  # Move up one level for '..'elif part != '' and part != '.':simplified_parts.append(part)simplified_path = '/' + '/'.join(simplified_parts)print(f'Original Absolute Path: {path}')print(f'Simplified Absolute Path: {simplified_path}')
# Example: Simplify an absolute path
simplify_absolute_path('/home/user/../documents/./file.txt')# 方向数组
dx=[-1,1,0,0,-1,1,-1,1]
dy=[0,0,-1,1,-1,1,1,-1]
#用于搜索树
for k in range(8):x,y=i+dx[k],j+dy[k]if 0<=x<=self.m and 0<=y <-self.n and 其他剪枝条件:recursion(x,y,...)

二、知识点

2.1 threading.timer、timers.timer、forms.timer区别

这三个都是计时器相关的类,但是应用场景不同。

threading.Timer 是 Python 内置的模块 threading 中的一个类,用于在一定时间后执行指定的函数。使用该计时器可以在多线程环境下执行延时操作,例如在一个主线程中启动一个子线程,等待一段时间后再执行一些操作。

timers.Timer 是一个第三方库 timers 中的一个类,用于控制在一定时间后执行指定的函数。和 threading.Timer 类似,不过这个库提供了更加灵活的计时器功能,可以定制计时器的精度,以及在计时器到期时执行的回调函数。

forms.Timer 是 windows Forms 应用程序框架中的一个计时器控件,可以在指定时间间隔内重复执行指定的事件处理程序。这个计时器通常用于 UI 界面的更新,例如定时更新进度条或者刷新数据。

总的来说,这三个计时器类都有自己的特点和应用场景,需要根据实际情况选择适合的计时器类。

2.2 浮点精度问题

Floating Point Arithmetic: Issues and Limitations

2.3 python中的False值

None
0
”” (empty string)
False
[]
{}
()

其他都是True

2.4 数组知识点

数组切片: ls[start:end:step]

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/876045.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

直线与曲线的交点

直线与曲线的交点 在数学和计算机图形学中&#xff0c;计算直线与曲线的交点通常涉及到解方程组的问题。这里以Python为例&#xff0c;介绍如何求解直线与二次曲线&#xff08;如抛物线&#xff09;的交点。 直线与抛物线的交点 假设我们有一条直线 (y mx b) 和一条抛物线 …

法制史学习笔记(个人向) Part5

法制史学习笔记(个人向) Part5 7. 宋朝法律制度 这里强烈推荐B站up主有点意思研究所和嘉佑生宣&#xff0c;宋史看他们基本齐了。 7.1 立法概况 7.1.1 宋刑统&#x1f338; 宋朝建立后不久&#xff0c;太祖赵匡胤即制定颁布了《宋建隆重详定刑统》&#xff0c;简称《宋刑统…

Jenkins 服务搭建以及自动化编译部署

安装环境&#xff1a;Ubuntu22.04 1.首先安装Jenkins 这是 Jenkins 的 Debian 软件包存储库&#xff0c;用于自动安装和升级。 要使用此存储库&#xff0c;请先将密钥添加到系统中&#xff0c;在服务器执行命令&#xff1a; curl -fsSL https://pkg.jenkins.io/debian-stable…

如何在 SpringBoot 中优雅的做参数校验?

一、故事背景 关于参数合法性验证的重要性就不多说了&#xff0c;即使前端对参数做了基本验证&#xff0c;后端依然也需要进行验证&#xff0c;以防不合规的数据直接进入服务器&#xff0c;如果不对其进行拦截&#xff0c;严重的甚至会造成系统直接崩溃&#xff01; 本文结合…

Windows下编译安装Kratos

Kratos是一款开源跨平台的多物理场有限元框架。本文记录在Windows下编译Kratos的流程。 Ref. from Kratos KRATOS Multiphysics ("Kratos") is a framework for building parallel, multi-disciplinary simulation software, aiming at modularity, extensibility, a…

昇思25天学习打卡营第24天|RNN实现情感分类

RNN实现情感分类学习总结 概述 情感分类是自然语言处理领域的重要任务&#xff0c;主要用于识别文本中表达的情绪。本文使用MindSpore框架实现基于RNN的情感分类模型&#xff0c;示例包括&#xff1a; 输入: “This film is terrible” -> 标签: Negative输入: “This fi…

UE5.4内容示例(1)- 学习笔记

https://www.unrealengine.com/marketplace/zh-CN/product/content-examples 《内容示例》是学习UE5的基础示例&#xff0c;可以用此示例熟悉一遍UE5的功能 模型与材质部分 StaticMeshes FBX_Import_Options Material_Advanced Material_Decals Material_Instances Material_N…

MySQL零散拾遗(八)--- MySQL正则表达式

MySQL 支持使用正则表达式进行模式匹配&#xff0c;这对于复杂的字符串处理非常有用。MySQL 中的正则表达式可以通过 REGEXP 或 RLIKE 运算符来实现。下面详细介绍 MySQL 中正则表达式的语法和一些常用的正则表达式模式。 正则表达式基础 锚点 ^: 匹配字符串开头$: 匹配字符串…

Python 高阶语法

前言&#xff1a; 我们通过上篇文章学习了Python的基础语法&#xff0c;接下来我们来学习Python的高阶语法 1.初识对象 在Python中我们可以做到和生活中那样&#xff0c;设计表格、生产表格、填写表格的组织形式的 面向对象包含 3 大主要特性&#xff1a;  封装  继承 …

Zilliz 推出 Spark Connector:简化非结构化数据处理流程

随着人工智能&#xff08;AI&#xff09;和深度学习&#xff08;Deep Learning&#xff09;技术的高速发展&#xff0c;使用神经网络模型将数据转化为 Embedding 向量 已成为处理非结构化数据并实现语义检索的首选方法&#xff0c;广泛应用于搜索、推荐系统等 AI 业务中。 以生…

架构建模-系统架构师(三十二)

1、DNS配置文件是&#xff08;&#xff09;&#xff0c;它包含了主机的域名搜索顺序和DNS服务器地址。 A /etc/hostname B /dev/host.conf C /etc/resolv.conf D /dev/name.conf 解析&#xff1a; 保存在etc/reolv.conf 2、信息隐蔽式开发整体程序时使用的法则&#xff0c…

C语言 定义结构体变量并计算该日在本年中是第几天

定义一个结构体变量(包括年、月、日)。计算该日在本年中是第几天,注意闰年问题&#xff08;即将闰年情况包含在内&#xff09;。 #include <stdio.h>typedef struct {int year;int month;int day; } Date;int isLeapYear(int year) {if ((year % 4 0 && year %…

力扣202.快乐数

202. 快乐数 - 力扣&#xff08;LeetCode&#xff09; 主要是用到了鸽巢原理&#xff0c;最后他们一定会重合&#xff0c;我们只需要判断类似&#xff0c;链表的成环相遇的时候是不是1就行了 class Solution { public:int bitsum(int n){int sum 0;while (n){int a 0;a n …

用护眼灯还需要开灯吗?护眼灯行业三大套路迷局揭秘

用护眼灯还需要开灯吗&#xff1f;在使用护眼台灯时&#xff0c;同时开启室内的主照明十分必要。如果关闭其他灯具&#xff0c;仅保留护眼台灯&#xff0c;那么只有台灯周围的小片区域能够被照亮&#xff0c;而房间的其他部分则处于相对昏暗的状态。这种明显的光线差异会造成视…

freertos的学习cubemx版

HAL 库的freertos 1 实时 2 任务->线程 3 移植 CMSIS_V2 V1版本 NVIC配置全部是抢占优先级 第四组 抢占级别有 0-15 编码规则&#xff0c; 变量名 &#xff1a;类型前缀&#xff0c; c - char S - int16_t L - int32_t U - unsigned Uc - uint8_t Us - uint…

Java常见的面试二

1、普通类和抽象类有那些区别 普通类中不能有抽象方法&#xff0c;抽象类中可以有抽象方法普通类可以直接实例化&#xff0c;抽象类不能直接实例化 2、抽象类能够使用final修饰吗 不能&#xff0c;抽象类是由子类继承的&#xff0c;但是final修饰的类不能被继承。两者矛盾所以…

《书生大模型实战营第3期》入门岛 学习笔记与作业:Python 基础知识

文章大纲 Python 简介1 安装Python1.1 什么是conda&#xff1f;1.1.1 功能与作用&#xff1a;1.1.2 常用命令&#xff1a;1.1.3 适用性&#xff1a; 1.2 Python安装与学习环境准备1.2.1 下载miniconda1.2.2 安装miniconda1.2.3 创建一个python练习专属的conda虚拟环境 2: Pytho…

【制作100个unity游戏之31】用unity制作一个爬坡2d赛车小游戏

最终效果 【制作100个unity游戏之31】用unity制作一个爬坡2d赛车小游戏 前言 今天用unity制作一个简单的爬坡2d赛车小游戏 素材 https://www.spriters-resource.com/mobile/hillclimbracing/ 拼装车素材 车身添加碰撞体&#xff0c;摩檫力0 轮胎添加碰撞体和刚体&#xff0…

【VSCode实战】Golang无法跳转问题竟是如此简单

上一讲【VSCode实战】Go插件依赖无法安装 – 经云的清净小站 (skycreator.top)&#xff0c;开头说到了在VSCode中Golang无法跳转的问题&#xff0c;但文章的最后也没给出解决方案&#xff0c;只解决了安装Go插件的依赖问题。 解决了插件依赖问题&#xff0c;无法跳转的问题也离…