配合以前两篇文章使用:
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 stringprint(f'Formatted Amount: {formatted_amount}')# 生成随机字符串import random
import string
defgenerate_random_string(length):
characters = string.ascii_letters + string.digits
random_string =''.join(random.choice(characters)for _ inrange(length))return random_string
# Generate a random string of length 8
random_string = generate_random_string(8)# Display the random stringprint(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 resultprint(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 resultprint(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 resultprint(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 datesif 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 removetry:
index_to_remove = original_list.index(item_to_remove)# Remove the item from the list
original_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 resultprint('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]# 数组分块defchunk_array(array, chunk_size):
result =[]for i inrange(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 resultprint('Original Array:', my_array)print('Chunks:', chunks)# 获取文件后缀defget_file_extension(file_name):# Split the file name based on the dot
parts = 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
defvalidate_email(email):# Regular expression for a basic email validation
email_regex =r'^[^\s@]+@[^\s@]+\.[^\s@]+$'# Test the email against the regular expressionreturn re.match(email_regex, email)isnotNone# Example usage:
email_to_validate ='[email protected]'if validate_email(email_to_validate):print('Email is valid')else:print('Email is not valid')# 一定时延后执行某函数import threading
defmy_function(parameter):print('Parameter received:', parameter)# Define the parameter
my_parameter ='Hello, world!'# Define a function to be executed after a delaydefdelayed_execution():
my_function(my_parameter)# Schedule the function to be executed after a delay
timer = threading.Timer(1.0, delayed_execution)
timer.start()# 函数重载(overloadding)defexample_function(*args):iflen(args)==0:# No arguments providedprint('No arguments')eliflen(args)==1andisinstance(args[0],int):# One argument of type number providedprint('One number argument:', args[0])eliflen(args)==2andisinstance(args[0],str)andisinstance(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)构造,FILOclassStack:def__init__(self):
self.items =[]# Push an element onto the stackdefpush(self, element):
self.items.append(element)# Pop the top element from the stackdefpop(self):if self.is_empty():return'Underflow'return self.items.pop()# Peek at the top element without removing itdefpeek(self):return self.items[-1]if self.items elseNone# Check if the stack is emptydefis_empty(self):returnlen(self.items)==0# Get the size of the stackdefsize(self):returnlen(self.items)# Print the stack elementsdefprint(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: 3print('Popped element:', stack.pop())# Outputs: 3print('Stack size:', stack.size())# Outputs: 2print('Is the stack empty?', stack.is_empty())# Outputs: False# 构建队列(Queue) FIFOclassQueue:def__init__(self):
self.items =[]# Enqueue an element at the end of the queuedefenqueue(self, element):
self.items.append(element)# Dequeue the element from the front of the queuedefdequeue(self):if self.is_empty():return'Underflow'return self.items.pop(0)# Peek at the front element without removing itdeffront(self):if self.is_empty():return'Queue is empty'return self.items[0]# Check if the queue is emptydefis_empty(self):returnlen(self.items)==0# Get the size of the queuedefsize(self):returnlen(self.items)# Print the queue elementsdefprint(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: 1print('Dequeued element:', queue.dequeue())# Outputs: 1print('Queue size:', queue.size())# Outputs: 2print('Is the queue empty?', queue.is_empty())# Outputs: False# 获取图片尺寸from PIL import Image
import requests
from io import BytesIO
defget_image_dimensions(image_url):try:# Make a request to get the image content
response = requests.get(image_url)# Open the image using PIL
img = Image.open(BytesIO(response.content))# Get the dimensions
width, 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
defgenerate_random_color():# Generate random values for red, green, and blue components
red = random.randint(0,255)
green = random.randint(0,255)
blue = random.randint(0,255)# Create the RGB color string
color =f'rgb({red}, {green}, {blue})'return color
# Example usage:
random_color = generate_random_color()print('Random Color:', random_color)# 随机密码生成import random
import string
defgenerate_random_password(length):# Define character sets
uppercase_chars = string.ascii_uppercase
lowercase_chars = string.ascii_lowercase
numeric_chars = string.digits
special_chars ='!@#$%^&*()-_+='# Combine character sets
all_chars = uppercase_chars + lowercase_chars + numeric_chars + special_chars
# Check if the input length is a valid positive numberifnotisinstance(length,int)or length <=0:return'Invalid input. Please provide a positive integer for the password length.'# Generate the random password
password =''.join(random.choice(all_chars)for _ inrange(length))return password
# Example usage:
password_length =12
random_password = generate_random_password(password_length)print(f'Generated Password: {random_password}')# 二进制字符串转换为数字defbinary_to_decimal(binary_string):# Check if the input is a valid binary stringifnotall(char in'01'for char in binary_string):return'Invalid input. Please provide a valid binary string.'# Convert binary to decimal
decimal_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 resultprint('Original Dictionary:')print(person)print('\nJSON-formatted String:')print(json_string)# RGB 转 HEXdefconvert_to_hex(red, green, blue):defto_hex(value):
hex_value =format(value,'02x')return hex_value
hex_red = to_hex(red)
hex_green = to_hex(green)
hex_blue = to_hex(blue)returnf'#{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.parseimport re
defbreak_url(url):
url_parts ={}
url_regex =r'^(\w+):\/\/([\w.-]+)(\/.*)?$'
matches = re.match(url_regex, url)ifnot matches:print('Invalid URL format.')return
url_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')# 替换路径中的..和.defsimplify_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 inrange(8):
x,y=i+dx[k],j+dy[k]if0<=x<=self.m and0<=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值
None0
”” (empty string)False[]{}()
其他都是True
2.4 数组知识点
数组切片:
ls[start:end:step]
版权归原作者 Code_LT 所有, 如有侵权,请联系我们删除。