【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.digits
random_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 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 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 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
def validate_email(email):
# Regular expression for a basic email validation
email_regex = r'^[^\s@]+@[^\s@]+\.[^\s@]+$'
# Test the email against the regular expression
return 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 provided
print('No arguments')
elif len(args) == 1 and isinstance(args[0], int):
# One argument of type number provided
print('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 number
print('String and number arguments:', args[0], args[1])
else:
# Default case
print('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 stack
def push(self, element):
self.items.append(element)
# Pop the top element from the stack
def pop(self):
if self.is_empty():
return 'Underflow'
return self.items.pop()
# Peek at the top element without removing it
def peek(self):
return self.items[-1] if self.items else None
# Check if the stack is empty
def is_empty(self):
return len(self.items) == 0
# Get the size of the stack
def size(self):
return len(self.items)
# Print the stack elements
def 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 queue
def enqueue(self, element):
self.items.append(element)
# Dequeue the element from the front of the queue
def dequeue(self):
if self.is_empty():
return 'Underflow'
return self.items.pop(0)
# Peek at the front element without removing it
def front(self):
if self.is_empty():
return 'Queue is empty'
return self.items[0]
# Check if the queue is empty
def is_empty(self):
return len(self.items) == 0
# Get the size of the queue
def size(self):
return len(self.items)
# Print the queue elements
def 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 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 dimensions
print('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 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
def generate_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 number
if not isinstance(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 _ 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 string
if not all(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 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_value
hex_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.')
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')
# 替换路径中的..和.
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]
原文地址:https://blog.csdn.net/Code_LT/article/details/140146803
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!