自定義列表Python四則運算
數碼 2
本文將介紹如何在Python中自定義列表的四則運算功能。
在Python中,列表是一種有序的可變序列,可以通過直接使用+,*等符號對列表進行基礎的運算。
list1 = [1,2,3]
list2 = [4,5,6]
list3 = list1 + list2 #列表拼接
list4 = list1 * 3 #列表複製
print(list3) #[1, 2, 3, 4, 5, 6]
print(list4) #[1, 2, 3, 1, 2, 3, 1, 2, 3]
我們可以定義一個函數add,來實現兩個列表的加法。
def add(list1, list2):
if len(list1) != len(list2): #若列表長度不同,則無法加法運算
return None
else:
return [list1[i]+list2[i] for i in range(len(list1))] #逐個元素相加
list1 = [1,2,3]
list2 = [4,5,6]
print(add(list1, list2)) #[5, 7, 9]
同理,我們也可以定義函數sub,來實現列表減法。
def sub(list1, list2):
if len(list1) != len(list2): #若列表長度不同,則無法減法運算
return None
else:
return [list1[i]-list2[i] for i in range(len(list1))] #逐個元素相減
list1 = [1,2,3]
list2 = [4,5,6]
print(sub(list1, list2)) #[-3, -3, -3]
列表乘法可以實現向量的數乘或矩陣的數乘。
def mul(list1, n):
return [list1[i]*n for i in range(len(list1))] #逐個元素數乘
list1 = [1,2,3]
print(mul(list1, 2)) #[2, 4, 6]
列表除法可以實現向量的數乘的相反方向除以一個數的運算。
def div(list1, n):
if n == 0: #若除數為0,則無法運算
return None
else:
return [list1[i]/n for i in range(len(list1))] #逐個元素除以給定數
list1 = [1,2,3]
print(div(list1, 2)) #[0.5, 1.0, 1.5]
自定義列表四則運算可以用於向量運算、矩陣相加減、平面的變換等實際問題的解決。
list1 = [1,2,3] #向量
list2 = [4,5,6]
print('向量加法:', add(list1, list2))
print('向量減法:', sub(list1, list2))
print('向量數乘:', mul(list1, 2))
例如,我們可以利用自定義列表四則運算實現平面的沿x軸方向縮放。
import matplotlib.pyplot as plt
x = [1,2,3]
y = [2,4,6]
def scale_x(x, fac):
return mul(x, fac)
x_scale = scale_x(x, 2) #沿x軸方向放大2倍
y_scale = y
plt.plot(x, y, label='original')
plt.plot(x_scale, y_scale, label='scaled')
plt.legend()
plt.show()
本文介紹了如何在Python中自定義列表的四則運算功能,並且利用這一功能解決了實際問題。自定義列表四則運算可以增強Python的運算能力,為實際應用提供便利。