处理数学运算和排列组合
1. 基本算术运算
进行基本算术运算:
sum = 7 + 3 # 加法
difference = 7 - 3 # 减法
product = 7 * 3 # 乘法
quotient = 7 / 3 # 除法
remainder = 7 % 3 # 模运算(取余数)
power = 7 ** 3 # 指数运算
2. 复数运算
处理复数:
z = complex(2, 3) # 创建复数 2 + 3j
real_part = z.real # 获取实部
imaginary_part = z.imag # 获取虚部
conjugate = z.conjugate() # 获取共轭复数
3. 数学函数
常见的数学函数:
import math
root = math.sqrt(16) # 平方根
logarithm = math.log(100, 10) # 以10为底100的对数
sine = math.sin(math.pi / 2) # 正弦值(以弧度计的90度)
4. 生成排列组合
从给定集合生成排列的简单方法:
from itertools import permutations
paths = permutations([1, 2, 3]) # 生成列表[1, 2, 3]的所有排列组合
for path in paths:
print(path)
5. 生成组合
生成组合的简单方法:
from itertools import combinations
combos = combinations([1, 2, 3, 4], 2) # 生成所有2元素组合
for combo in combos:
print(combo)
6. 随机数生成
获取随机数:
import random
num = random.randint(1, 100) # 生成1到100之间的随机整数
7. 处理分数
当需要处理分数时:
from fractions import Fraction
f = Fraction(3, 4) # 创建分数 3/4
print(f + 1) # 分数加整数
8. 统计函数
获取平均值、中位数和标准差:
import statistics
data = [1, 2, 3, 4, 5]
mean = statistics.mean(data) # 平均值
median = statistics.median(data) # 中位数
stdev = statistics.stdev(data) # 标准差
9. 三角函数
处理三角函数:
import math
angle_rad = math.radians(60) # 将60度转换为弧度
cosine = math.cos(angle_rad) # 余弦值
10. 处理无穷大和NaN
处理无穷大和NaN:
import math
infinity = math.inf # 表示无穷大
not_a_number = math.nan # 表示非数字(NaN)
数据库操作
1. 建立连接
连接到Postgres数据库:
import psycopg2
connection = psycopg2.connect(
dbname='your_database',
user='your_username',
password='your_password',
host='your_host'
)
2. 创建游标
创建数据库游标,用于遍历和操作记录:
cursor = connection.cursor()
3. 执行查询
从数据库中选择数据:
cursor.execute("SELECT * FROM your_table")
4. 获取查询结果
使用游标获取数据:
records = cursor.fetchall()
for record in records:
print(record)
5. 插入记录
向数据库表中插入数据:
cursor.execute("INSERT INTO your_table (column1, column2) VALUES (%s, %s)", ('value1', 'value2'))
connection.commit() # 提交事务
6. 更新记录
修改记录:
cursor.execute("UPDATE your_table SET column1 = %s WHERE column2 = %s", ('new_value', 'condition_value'))
connection.commit()
7. 删除记录
从表中删除记录:
cursor.execute("DELETE FROM your_table WHERE condition_column = %s", ('condition_value',))
connection.commit()
8. 创建表格
创建新表格,定义其结构:
cursor.execute("""
CREATE TABLE your_new_table (
id SERIAL PRIMARY KEY,
column1 VARCHAR(255),
column2 INTEGER
)
""")
connection.commit()
9. 删除表格
删除表格:
cursor.execute("DROP TABLE if exists your_table")
connection.commit()
10. 使用事务
使用事务确保原子性:
try:
cursor.execute("your first transactional query")
cursor.execute("your second transactional query")
connection.commit() # 如果一切顺利则提交
except Exception as e:
connection.rollback() # 如果出现任何问题则回滚
print(f"An error occurred: {e}")
总结
今天主要总结了Python中数据运算和数据库相关操作,明天继续。