织梦网站案例,网站数据分析工具,新手制作网站,做网站对公司的作用配合以前两篇文章使用#xff1a; python易忘操作和小知识点集锦 常用算法模板与知识点
使用 Python 3.x
一、小功能
# 把数字转换为货币字符串
import locale
# Set the locale to United States
locale.setlocale(locale.LC_ALL, en_US.UTF-8)
# Example number
amount …配合以前两篇文章使用 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, groupingTrue)
# Display the formatted currency string
print(fFormatted 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(fRandom 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(fOriginal String: {original_string})
print(fBase64 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(fFormatted 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(fCurrent 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:ichunk_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(fFile 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 exampleemail.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 Underflowreturn 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 Underflowreturn self.items.pop(0)# Peek at the front element without removing itdef front(self):if self.is_empty():return Queue is emptyreturn 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 frgb({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(fGenerated 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(fThe 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(fHEX: {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(fOriginal Absolute Path: {path})print(fSimplified 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,yidx[k],jdy[k]if 0xself.m and 0y -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]