Python实现常见的序列运算:翻转、相乘、相加、点积、累加、卷积。
时间: 2023-07-03 11:20:00 浏览: 140
好的,我来分别介绍一下Python实现常见的序列运算。
1. 翻转:使用切片[::-1]即可将序列翻转,例如:
```python
a = [1, 2, 3, 4, 5]
b = a[::-1]
print(b) # [5, 4, 3, 2, 1]
```
2. 相乘:使用乘法符号*即可将序列相乘,例如:
```python
a = [1, 2, 3]
b = a * 3
print(b) # [1, 2, 3, 1, 2, 3, 1, 2, 3]
```
3. 相加:使用加法符号+即可将序列相加,例如:
```python
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c) # [1, 2, 3, 4, 5, 6]
```
4. 点积:使用zip函数和列表推导式即可计算序列的点积,例如:
```python
a = [1, 2, 3]
b = [4, 5, 6]
dot_product = sum([i*j for i, j in zip(a, b)])
print(dot_product) # 32
```
5. 累加:使用列表推导式和累加器即可计算序列的累加和,例如:
```python
a = [1, 2, 3, 4, 5]
sum_a = sum([i for i in a])
print(sum_a) # 15
```
6. 卷积:使用numpy库中的convolve函数即可计算序列的卷积,例如:
```python
import numpy as np
a = [1, 2, 3]
b = [4, 5, 6]
conv_ab = np.convolve(a, b, mode='full')
print(conv_ab) # [4, 13, 28, 27, 18]
```
以上是Python实现常见的序列运算的方法,希望能对你有所帮助。
阅读全文