当前位置: 首页 > news >正文

【Python基础】 17 Rust 与 Python 运算符对比学习笔记

一、算术运算符

运算符Rust 🦀Python 🐍示例 (Rust)示例 (Python)说明
+加法加法let sum = 5 + 3;sum = 5 + 3
-减法减法let diff = 5 - 3;diff = 5 - 3
*乘法乘法let product = 5 * 3;product = 5 * 3
/除法除法let quotient = 5 / 3;1quotient = 5 / 31.666...
%取余取模let remainder = 5 % 3;2remainder = 5 % 32
**幂运算result = 2 ** 38
//整除result = 5 // 22
关键差异:
  • 除法:Rust 整数除法会截断小数,Python 会返回浮点数
  • 幂运算:Rust 使用 pow() 方法,Python 使用 **
  • 整除:Python 有专门的 // 运算符
// Rust 算术运算
let a = 10;
let b = 3;println!("加法: {}", a + b);      // 13
println!("减法: {}", a - b);      // 7
println!("乘法: {}", a * b);      // 30
println!("除法: {}", a / b);      // 3 (整数除法)
println!("取余: {}", a % b);      // 1
println!("幂运算: {}", a.pow(b)); // 1000
# Python 算术运算
a = 10
b = 3print(f"加法: {a + b}")      # 13
print(f"减法: {a - b}")      # 7
print(f"乘法: {a * b}")      # 30
print(f"除法: {a / b}")      # 3.333... (浮点除法)
print(f"取余: {a % b}")      # 1
print(f"幂运算: {a ** b}")   # 1000
print(f"整除: {a // b}")     # 3

二、比较运算符

运算符Rust 🦀Python 🐍说明
==相等相等值相等
!=不等不等值不相等
>大于大于
<小于小于
>=大于等于大于等于
<=小于等于小于等于
关键差异:
  • 返回值:Rust 返回 bool,Python 返回 bool
  • 类型严格性:Rust 要求比较的操作数类型必须相同
// Rust 比较运算
let x = 5;
let y = 10;println!("相等: {}", x == y);    // false
println!("不等: {}", x != y);    // true
println!("大于: {}", x > y);     // false
println!("小于: {}", x < y);     // true// 类型必须匹配
// let result = 5 == 5.0; // 错误!不能比较 i32 和 f64
# Python 比较运算
x = 5
y = 10print(f"相等: {x == y}")    # False
print(f"不等: {x != y}")    # True
print(f"大于: {x > y}")     # False
print(f"小于: {x < y}")     # True# 类型可以不同(但通常不建议)
print(f"混合类型: {5 == 5.0}")  # True

三、逻辑运算符

运算符Rust 🦀Python 🐍说明
&&逻辑与and两者都为真
``逻辑或
!逻辑非not取反

关键差异:

  • 语法不同:Rust 使用符号,Python 使用关键字
  • 短路求值:两者都支持短路求值
// Rust 逻辑运算
let a = true;
let b = false;println!("与: {}", a && b);   // false
println!("或: {}", a || b);   // true
println!("非: {}", !a);       // false// 短路求值
let mut count = 0;
let result = false && {count += 1;true
};
println!("Count: {}", count); // 0 (短路,未执行)
# Python 逻辑运算
a = True
b = Falseprint(f"与: {a and b}")   # False
print(f"或: {a or b}")    # True
print(f"非: {not a}")     # False# 短路求值
count = 0
result = False and (count := count + 1)  # 使用海象运算符
print(f"Count: {count}")  # 0 (短路,未执行)

四、位运算符

运算符Rust 🦀Python 🐍说明
&按位与按位与
|按位或按位或
^按位异或按位异或
!按位取反~取反
<<左移左移
>>右移右移
关键差异:
  • 取反运算符:Rust 用 !,Python 用 ~
  • 移位行为:Rust 有算术移位和逻辑移位之分
// Rust 位运算
let a: u8 = 0b1010; // 10
let b: u8 = 0b1100; // 12println!("与: {:08b}", a & b);   // 00001000 (8)
println!("或: {:08b}", a | b);   // 00001110 (14)
println!("异或: {:08b}", a ^ b); // 00000110 (6)
println!("取反: {:08b}", !a);    // 11110101 (245)
println!("左移: {:08b}", a << 2); // 00101000 (40)
println!("右移: {:08b}", a >> 1); // 00000101 (5)
# Python 位运算
a = 0b1010  # 10
b = 0b1100  # 12print(f"与: {a & b:08b}")   # 00001000 (8)
print(f"或: {a | b:08b}")   # 00001110 (14)
print(f"异或: {a ^ b:08b}") # 00000110 (6)
print(f"取反: {~a & 0xFF:08b}") # 11110101 (245) - 需要掩码
print(f"左移: {a << 2:08b}") # 00101000 (40)
print(f"右移: {a >> 1:08b}") # 00000101 (5)

五、赋值运算符

运算符Rust 🦀Python 🐍说明
=赋值赋值基本赋值
+=加后赋值加后赋值
-=减后赋值减后赋值
*=乘后赋值乘后赋值
/=除后赋值除后赋值
%=取余后赋值取模后赋值
**=幂后赋值
//=整除后赋值

关键差异:

  • Python 有更多复合赋值运算符
  • Rust 需要变量声明为 mut 才能修改
// Rust 赋值运算
let mut x = 10;
x += 5;    // x = 15
x -= 3;    // x = 12
x *= 2;    // x = 24
x /= 4;    // x = 6
x %= 4;    // x = 2// 需要 mut 关键字
// let y = 10;
// y += 5; // 错误!y 不可变
# Python 赋值运算
x = 10
x += 5    # x = 15
x -= 3    # x = 12
x *= 2    # x = 24
x /= 4    # x = 6.0
x %= 4    # x = 2.0
x **= 3   # x = 8.0
x //= 2   # x = 4.0# 不需要特殊声明
y = 10
y += 5    # 可以直接修改

六、类型相关运算符

Rust 特有运算符
// 类型转换 as
let x: i32 = 10;
let y: f64 = x as f64; // 显式类型转换// 引用和解引用
let value = 42;
let ref_value = &value;    // 创建引用
let deref_value = *ref_value; // 解引用// 范围运算符 ..
for i in 0..5 {           // 0, 1, 2, 3, 4println!("{}", i);
}for i in 0..=5 {          // 0, 1, 2, 3, 4, 5println!("{}", i);
}

Python 特有运算符

# 身份运算符 is, is not
a = [1, 2, 3]
b = [1, 2, 3]
c = aprint(a is b)     # False - 不同对象
print(a is c)     # True - 同一对象
print(a == b)     # True - 值相等# 成员运算符 in, not in
numbers = [1, 2, 3, 4, 5]
print(3 in numbers)       # True
print(6 not in numbers)   # True# 海象运算符 := (Python 3.8+)
if (n := len(numbers)) > 3:print(f"列表有 {n} 个元素")

八、运算符重载

Rust 运算符重载
use std::ops::Add;#[derive(Debug)]
struct Point {x: i32,y: i32,
}impl Add for Point {type Output = Point;fn add(self, other: Point) -> Point {Point {x: self.x + other.x,y: self.y + other.y,}}
}let p1 = Point { x: 1, y: 2 };
let p2 = Point { x: 3, y: 4 };
let p3 = p1 + p2;
println!("{:?}", p3); // Point { x: 4, y: 6 }
Python 运算符重载
class Point:def __init__(self, x, y):self.x = xself.y = ydef __add__(self, other):return Point(self.x + other.x, self.y + other.y)def __repr__(self):return f"Point({self.x}, {self.y})"p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
print(p3)  # Point(4, 6)

九、优先级对比

Rust 运算符优先级(从高到低)
  1. () [] . ? !
  2. - ! * & &mut (一元)
  3. as
  4. * / %
  5. + -
  6. << >>
  7. &
  8. ^
  9. |
  10. == != < > <= >=
  11. &&
  12. ||
  13. .. ..=
  14. = += -= *= /= %= &= |= ^= <<= >>=
Python 运算符优先级(从高到低)
  1. () [] . {}
  2. ** (指数)
  3. +x -x ~x (一元)
  4. * / // %
  5. + -
  6. << >>
  7. &
  8. ^
  9. |
  10. == != < > <= >= is is not in not in
  11. not
  12. and
  13. or
  14. := (海象运算符)

九、总结对比

特性Rust 🦀Python 🐍
类型安全⭐⭐⭐⭐⭐ (编译时检查)⭐⭐⭐ (运行时检查)
运算符数量⭐⭐⭐⭐⭐⭐⭐⭐⭐
语法一致性⭐⭐⭐⭐⭐⭐⭐⭐⭐
学习曲线⭐⭐ (较陡峭)⭐⭐⭐⭐⭐ (平缓)
表达能力⭐⭐⭐⭐⭐⭐⭐⭐⭐
性能⭐⭐⭐⭐⭐⭐⭐⭐
选择建议:
  • 选择 Rust:需要高性能、内存安全、系统级编程
  • 选择 Python:需要快速开发、脚本编写、数据科学

关键记忆点:

  • Rust 使用符号逻辑运算符 (&&, ||, !)
  • Python 使用关键字逻辑运算符 (and, or, not)
  • Rust 整数除法会截断,Python 会返回浮点数
  • Rust 需要显式类型转换,Python 支持隐式转换
  • Python 有更多专用运算符 (**, //, in, is)

文章转载自:

http://weQTpqus.wypyL.cn
http://8gZUiNap.wypyL.cn
http://jmgoHPhe.wypyL.cn
http://M9oOHXSj.wypyL.cn
http://xBFf0eqs.wypyL.cn
http://aguDGfYL.wypyL.cn
http://EEALT2fr.wypyL.cn
http://JwaQElaR.wypyL.cn
http://NEtglRPi.wypyL.cn
http://8JWHPaJd.wypyL.cn
http://H59Aub01.wypyL.cn
http://xV5vzrDx.wypyL.cn
http://PnDUKFFg.wypyL.cn
http://rGmVrCSZ.wypyL.cn
http://B1vNLqRr.wypyL.cn
http://odLnNerM.wypyL.cn
http://V3URWYNB.wypyL.cn
http://jTzGwfdh.wypyL.cn
http://bG8OVVZP.wypyL.cn
http://WQYrw0j0.wypyL.cn
http://Nc1e8DzN.wypyL.cn
http://6fK64A1l.wypyL.cn
http://VTF5gIZT.wypyL.cn
http://pU1Ag1kN.wypyL.cn
http://zQRXENPy.wypyL.cn
http://8j23vtDe.wypyL.cn
http://LhWtqvKc.wypyL.cn
http://oY1qZFfF.wypyL.cn
http://wWioR22N.wypyL.cn
http://0XlvqYuF.wypyL.cn
http://www.dtcms.com/a/368388.html

相关文章:

  • 云手机可以息屏挂手游吗?
  • 会话管理巅峰对决:Spring Web中Cookie-Session、JWT、Spring Session + Redis深度秘籍
  • 腾讯云大模型训练平台
  • iPhone17全系优缺点分析,加持远程控制让你的手机更好用!
  • 数据泄露危机逼近:五款电脑加密软件为企业筑起安全防线
  • 阿里云vs腾讯云按量付费服务器
  • DocuAI深度测评:自动文档生成工具如何高效产出规范API文档与数据库表结构文档?
  • React JSX 语法讲解
  • 工厂办公环境如何实现一台服务器多人共享办公
  • 从 0 到 1 学 sed 与 awk:Linux 文本处理的两把 “瑞士军刀”
  • VNC连接服务器实现远程桌面-针对官方给的链接已经失效问题
  • 【Web】理解CSS媒体查询
  • 编写前端发布脚本
  • 无密码登录与设备信任:ABP + WebAuthn/FIDO2
  • 消息队列-ubutu22.04环境下安装
  • Vue3源码reactivity响应式篇之EffectScope
  • 从Java全栈到前端框架:一位程序员的实战之路
  • 【Java实战㉖】深入Java单元测试:JUnit 5实战指南
  • 【AI论文】Robix:一种面向机器人交互、推理与规划的统一模型
  • C++(Qt)软件调试---bug排查记录(36)
  • yolov8部署在一台无显卡的电脑上,实时性强方案
  • Alibaba Cloud Linux 3 安装Docker
  • SQL面试题及详细答案150道(61-80) --- 多表连接查询篇
  • 详细解读Docker
  • 【OJ】C++ vector类OJ题
  • 【数据库】MySQL 数据库创建存储过程及使用场景详解
  • Ubuntu22.04-ROS2下navgation2编译到运行
  • OpenLayers常用控件 -- 章节四:图层控制与切换教程
  • [ubuntu][C++]onnxruntime安装cpu版本后测试代码
  • 一个专为地图制图和数据可视化设计的在线配色网站,可以助你制作漂亮的地图!