考点
Arrays and NumPy
- 打印数组:
print(<np_array>)
- 打印数组形状:
print(<np_array>.shape)
- 打印第一行:
print(<np_array>[0])
- 打印中间列:
print(<np_array>[:, 1])
- 打印每一列的和:
print(np.sum(<np_array>, axis=0))
- 打印所有元素乘以10:
print(<np_array> * 10)
- 返回最大的行:
np.max(<np_array>)
- 返回最大的行对应的行号:
np.argmax(<np_array>)
- 取两列的差值:
<np_array>[:, 1] - <np_array>[:, 0]
Class Special Method
__setitem__(self, <index>)
: 语法糖, 用于以索引的方式设定一个对象内存储的值__getitem__(self, <index>)
: 语法糖, 用于以索引的方式获取一个对象内存储的值__str__(self)
: 调用print(<object>)
时自定义打印类的信息__len__(self)
: 返回对象的长度, 由len(<object>)
调用__repr__(self)
: 调用repr(<object>)
时自定义打印类的信息vars(<object>)
: 检查对象的属性, 以列表的形式返回__name__
: 类名__doc__
: 类的文档字符串, 在类的开头以'
的形式定义__dict__
: 类的属性, 包含了一个字典, 由类的数据属性组成, 和var(<object>)
类似, 但是有一些细微区别
例子
class Car:
def __init__(self, brand, model, price):
self.brand = brand
self.model = model
self.price = price
class CarCollection:
def __init__(self):
self.cars = []
def add_car(self, car):
self.cars.append(car)
def total_value(self):
return sum(car.price for car in self.cars)
# Special method to implement len function
def __len__(self):
return len(self.cars)
# Special method to add the ability to index the collection object
def __getitem__(self, index):
return self.cars[index]
# Special method to return a string representation of the CarCollection object
def __str__(self):
car_info = ", ".join(f"{car.brand} {car.model}" for car in self.cars)
return f"CarCollection with {len(self)} cars: {car_info}"
# Example usage
car1 = Car("Toyota", "Camry", 24000)
car2 = Car("Honda", "Civic", 22000)
collection = CarCollection()
collection.add_car(car1)
collection.add_car(car2)
# Using vars() to display details of each car
for car in collection:
print(vars(car))
print(collection) # Shows the car collection -> CarCollection with 2 cars: Toyota Camry, Honda Civic
print("Total value:", collection.total_value()) # Outputs the total price of the cars
print("Number of cars:", len(collection)) # -> 2
print("First car:", collection[0]) # -> First car: <__main__.Car object at *****>
Class Inheritance
由于子类的构造函数会覆盖掉父类的构造函数, 可以通过super().__init__(<attr>, ...)
来引入其父类的构造函数, 然后在这个基础上增加新的功能. 同样的, 也可以在子类的任意函数中通过super()
调用父类的任意函数, 注意, 和其他方法不同的是, 不用传入self
.
Shell Script
echo
: 用来输出文字#!/bin/bash
: 指定shell为bash shelltouch
: 用于创建文件>
: 重定向符cat
: 打印文件内容
Dict&Set Comprehension
写法和list comprehension差不多.
例子
Decorator
注意有两种写法:
例子
-
不带有参数的装饰器
-
带有参数的装饰器
例子
###### TASK 3 ######
import time
# Define the decorator
def measure_time(func):
def wrapper(n):
start = time.time()
result = func(n)
end = time.time()
execution_time = end - start
print(f"Time taken to execute: {execution_time} seconds")
return result
return wrapper
# Apply the decorator to a function
@measure_time
def factorial_iterative(n):
result = 1
for i in range(2, n+1):
result *= i
return result
# Call the function
print(factorial_iterative(25)) # Output: 15511210043330985984000000
#Expected output
'''
Time taken to execute: <time> seconds
15511210043330985984000000
'''
###### TASK 1 ######
# Define the decorator
def log_execution(func):
def wrapper():
print("Executing function...")
func()
print("Function executed!")
return wrapper
# Apply the decorator to a function
@log_execution
def greet():
print("Hello, welcome!")
# Call the function
greet()
#Expected Output
'''Executing function...
Hello, welcome!
Function executed!'''
###### TASK 2 ######
# Define the decorator
def validate_args(func):
def wrapper(x, y):
try:
result = func(x, y)
return result
except:
print("Invalid argument!")
return None
return wrapper
# Apply the decorator to a function
@validate_args
def add(x, y):
return x + y
# Call the function with valid arguments
print(add(2, 3)) # Output: 5
# Call the function with an invalid argument
print(add(2, "three")) # Output: Invalid argument!
#Expected Output
'''
5
Invalid argument!
None
'''
Generator
如果列表元素可以在循环的过程中不断算出后面的元素, 那么就不必创造出完整的列表, 节省大量空间. 在Python中, 这种边循环边计算的机制, 叫做生成器.
有两种方式创建生成器: 第一种和list comprehension类似, 只不过用的是()
; 第二种是生成器函数, 它在每次调用next()
的时候执行, 在函数内遇到yield
语句执行并中断, 再次执行的时候从上次返回的yield
语句的下一句开始执行.
例子
def odd():
print("step 1")
yield 1
print("step 2")
yield 3
print("step 3")
yield 5
o = odd()
next(o) # 输出step 1, 1
next(o) # 输出step 2, 3
next(o) # 输出step 3, 5
需要注意的是, 调用生成器函数会创建一个生成器对象, 如上面的o = odd()
. 多次调用生成器函数会创建多个相互独立的生成器对象.
例子
If Statement
什么, If statement居然放在Advanced???? 课题组在想什么??? 幼儿园也会写这个啊?
Lambda Function
Regular Expressions
需要先导入包import re
.
.
: 匹配任意单个字符, 可以用\.
转义^
: 匹配字符串的开始$
: 匹配字符串的结束*
: 匹配前面的字符0次或者多次+
: 匹配前面的字符1次或者多次?
: 匹配前面的字符0次或者1次{n}
: 精确匹配前面的字符n次{n,}
: 至少匹配前面的字符n次{n,m}
: 匹配前面的字符n到m次[abc]
: 匹配字符a, b或c[a-z]
: 匹配所有小写字母[^abc]
: 匹配除a, b, c以外的所有字符\d
: 匹配任意数字, 等价于[0-9]
\D
: 匹配任意非数字\w
: 匹配字母, 数字或下划线, 等价于[a-zA-Z0-9_]
\W
: 匹配任意非字母, 数字或下划线\s
: 匹配空白字符(空格, 制表符等)\S
: 匹配非空白字符()
: 分组或者捕获(?P<<name>>)
: 命名组
使用re.search(<pattern>, <input>)
检查input
是否match pattern. 如果match, 返回一个re.Match
对象, 如果不match, 返回None
.
复合:
.*
: 匹配任意长度的字符串
例子
import re
# 匹配含有python或者Python的句子
with open("./files/python.txt", "r") as f:
lines = f.readlines()
for line in lines:
if re.search(r".*[pP]ython.*", line.replace("\n", "")):
print(line.replace("\n", ""))
import re
# 匹配含有hello.world的句子
with open("./files/dots.txt", "r") as f:
lines = f.readlines()
for line in lines:
if re.search(r".*hello\.world.*", line.replace("\n", "")):
print(line.replace("\n", ""))
import re
# 匹配结尾为done的句子
with open("./files/done.txt", "r") as f:
lines = f.readlines()
for line in lines:
if re.search(r"done$", line.replace("\n", "")):
print(line.replace("\n", ""))
import re
# 匹配含有非数字的句子
with open("./files/mix.txt", "r") as f:
lines = f.readlines()
for line in lines:
if re.search(r".*\D.*", line.replace("\n", "")):
print(line.replace("\n", ""))
import re
# 提取字母, 数字或者混合
with open("./files/alphanumeric.txt", "r") as f:
lines = f.readlines()
for line in lines:
result = re.findall(r'[a-zA-Z0-9]+', line)
print(result)
import re
# 使用组提取信息
def extract_info(filename):
pattern = r"^([A-Z]{1}[a-z]*).(\d{2}).*([A-Z]{1}[a-z]*)$"
with open(filename, 'r') as file:
for line in file:
match = re.search(pattern, line)
if match:
# Group 1: Name, Group 2: Age, Group 3: Location
name = match.group(1)
age = match.group(2)
location = match.group(3)
print(f"Name: {name}, Age: {age}, Location: {location}")
# Call the function with the input file
extract_info('files/data.txt')