python用split分开数字和加减乘除等符号
时间: 2023-05-26 10:04:00 浏览: 77
可以使用正则表达式来分离数字和运算符号。
示例代码:
```python
import re
expr = "2+3*4-5/2"
# 定义正则表达式
pattern = r'(\d+|[+\-*/])'
# 利用正则表达式匹配数字和运算符号
tokens = re.findall(pattern, expr)
print(tokens) # ['2', '+', '3', '*', '4', '-', '5', '/', '2']
```
在上面的例子中,`(\d+|[+\-*/])` 是一个正则表达式,表示匹配连续的数字或者加减乘除符号。 `re.findall()` 函数会返回一个列表,其中包含了匹配到的所有字符串。
注意,符号 `+`、`-`、`*` 和 `/` 在正则表达式中有特殊含义,需要用反斜杠转义,即写成 `\+`、`\-`、`\*` 和 `\/`。
相关问题
python任意输入两个数字 输出加减乘除的结果
好的,以下是一个简单的 Python 代码,可以实现任意输入两个数字,并输出它们的加减乘除结果:
```python
a = float(input("请输入第一个数字:"))
b = float(input("请输入第二个数字:"))
# 加法
print("加法结果:", a + b)
# 减法
print("减法结果:", a - b)
# 乘法
print("乘法结果:", a * b)
# 除法
if b != 0:
print("除法结果:", a / b)
else:
print("除数不能为 0!")
```
你可以将以上代码复制到 Python IDE 中运行,输入任意的两个数字,即可得到它们的加减乘除结果。
python用类实现向量加减乘除
可以通过定义一个向量类来实现向量的加减乘除操作。以下是示例代码:
```python
import numpy as np
class Vector:
def __init__(self, data):
self.data = np.array(data)
def __add__(self, other):
if isinstance(other, Vector):
return Vector(self.data + other.data)
else:
raise TypeError("Unsupported operand type for +")
def __sub__(self, other):
if isinstance(other, Vector):
return Vector(self.data - other.data)
else:
raise TypeError("Unsupported operand type for -")
def __mul__(self, other):
if isinstance(other, (int, float)):
return Vector(self.data * other)
elif isinstance(other, Vector):
return np.dot(self.data, other.data)
else:
raise TypeError("Unsupported operand type for *")
def __truediv__(self, other):
if isinstance(other, (int, float)):
return Vector(self.data / other)
else:
raise TypeError("Unsupported operand type for /")
def __repr__(self):
return f"Vector({self.data})"
```
在这个向量类中,定义了向量加减乘除的运算符重载方法。可以使用 Vector([1, 2, 3]) 来创建一个向量对象,然后调用向量的加减乘除方法来进行相应的操作。示例代码如下:
```python
# 定义两个向量
a = Vector([1, 2, 3])
b = Vector([4, 5, 6])
# 向量加法
c = a + b
print("向量加法结果:", c)
# 向量减法
d = a - b
print("向量减法结果:", d)
# 向量数乘
k = 2
e = k * a
print("向量数乘结果:", e)
# 向量点乘
f = a * b
print("向量点乘结果:", f)
```
输出结果为:
```
向量加法结果: Vector([5 7 9])
向量减法结果: Vector([-3 -3 -3])
向量数乘结果: Vector([2 4 6])
向量点乘结果: 32
```
需要注意的是,在进行向量加减法时,要确保两个向量的维度相同;在进行向量点乘时,要确保两个向量的长度相同。