当前位置: 首页 > news >正文

【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]

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • UE5C++中,NewObject<>()和CreateDefaultSubobject<>()的区别
  • 网络通信---UDP
  • C语言 写一个函数days,实现某日在本年中是第几天计算。
  • c++中grpc简单使用---函数介绍及其代码演示
  • 如何处理selenium Webdriver中的文本框?
  • Linux环境docker部署Firefox结合内网穿透远程使用浏览器测试
  • SpringBoot 日志
  • C:图案打印
  • C++——QT:保姆级教程,从下载到安装到用QT写出第一个程序
  • Android串口开发及读取完整数据的解决方法
  • Vite项目中根据不同打包命令配置不同的后端接口地址,proxy解决跨域
  • Linux中的文件操作
  • 学习java的设计模式
  • XPathParser类
  • 【React】详解如何获取 DOM 元素
  • 【mysql】环境安装、服务启动、密码设置
  • Docker: 容器互访的三种方式
  • Lsb图片隐写
  • vue 个人积累(使用工具,组件)
  • 彻底搞懂浏览器Event-loop
  • 初识 beanstalkd
  • 开发了一款写作软件(OSX,Windows),附带Electron开发指南
  • 入职第二天:使用koa搭建node server是种怎样的体验
  • 说说动画卡顿的解决方案
  • 腾讯优测优分享 | Android碎片化问题小结——关于闪光灯的那些事儿
  • 新版博客前端前瞻
  • 在weex里面使用chart图表
  • 阿里云服务器购买完整流程
  • 数据库巡检项
  • ​ ​Redis(五)主从复制:主从模式介绍、配置、拓扑(一主一从结构、一主多从结构、树形主从结构)、原理(复制过程、​​​​​​​数据同步psync)、总结
  • ​​​​​​​ubuntu16.04 fastreid训练过程
  • ​插件化DPI在商用WIFI中的价值
  • # 透过事物看本质的能力怎么培养?
  • #我与Java虚拟机的故事#连载19:等我技术变强了,我会去看你的 ​
  • (C#)Windows Shell 外壳编程系列4 - 上下文菜单(iContextMenu)(二)嵌入菜单和执行命令...
  • (function(){})()的分步解析
  • (k8s中)docker netty OOM问题记录
  • (Redis使用系列) Springboot 使用redis实现接口幂等性拦截 十一
  • (八)五种元启发算法(DBO、LO、SWO、COA、LSO、KOA、GRO)求解无人机路径规划MATLAB
  • (二)换源+apt-get基础配置+搜狗拼音
  • (二十一)devops持续集成开发——使用jenkins的Docker Pipeline插件完成docker项目的pipeline流水线发布
  • (精确度,召回率,真阳性,假阳性)ACC、敏感性、特异性等 ROC指标
  • (免费领源码)Java#ssm#MySQL 创意商城03663-计算机毕业设计项目选题推荐
  • (三)Kafka 监控之 Streams 监控(Streams Monitoring)和其他
  • (十一)手动添加用户和文件的特殊权限
  • (一)u-boot-nand.bin的下载
  • (原創) 博客園正式支援VHDL語法著色功能 (SOC) (VHDL)
  • (转)自己动手搭建Nginx+memcache+xdebug+php运行环境绿色版 For windows版
  • .Net Core webapi RestFul 统一接口数据返回格式
  • .net core webapi Startup 注入ConfigurePrimaryHttpMessageHandler
  • .Net 垃圾回收机制原理(二)
  • .NET 设计模式初探
  • .net 微服务 服务保护 自动重试 Polly
  • .NET单元测试
  • .Net环境下的缓存技术介绍