เราไม่ได้ใช้ List เพื่อเก็บคอลเลกชันของค่าเท่านั้น แต่ยังใช้ทำการคำนวณหรือดำเนินการทางคณิตศาสตร์อีกด้วย
ตัวอย่างที่ 1: ฟังก์ชันคณิตศาสตร์พื้นฐาน
import math
data = 21.6
print('The floor of 21.6 is:', math.floor(data))
ผลลัพธ์
The floor of 21.6 is: 21
การคำนวณ Weighted Average ของ List
ตัวอย่างที่ 2
cost = [23, 10, 5, 32, 41] weight = [10, 20, 30, 40, 50] total_weight = sum(weight) weighted_sum = sum(c * w for c, w in zip(cost, weight)) weighted_avg = weighted_sum / total_weight print(weighted_avg)
ผลลัพธ์
72.84444444444445
ตัวอย่างที่ 3: ฟังก์ชันตรีโกณมิติ
import math
degree = 180
radian = math.radians(degree)
print('The given angle is:', radian)
print('sin(x) is:', math.sin(radian))
print('cos(x) is:', math.cos(radian))
print('tan(x) is:', math.tan(radian))
ผลลัพธ์
The given angle is: 3.141592653589793 sin(x) is: 1.2246467991473532e-16 cos(x) is: -1.0 tan(x) is: -1.2246467991473532e-16
ฟังก์ชันคณิตศาสตร์ Python ที่ใช้บ่อย
ceil(x): คืนค่าจำนวนเต็มที่น้อยที่สุดที่มากกว่าหรือเท่ากับ xfloor(x): คืนค่าจำนวนเต็มที่มากที่สุดที่น้อยกว่าหรือเท่ากับ xfabs(x): คืนค่าสัมบูรณ์ของ xfactorial(x): คืนแฟกทอเรียลของ xfmod(x, y): คืนเศษเมื่อ x หาร yfsum(iterable): คืนผลรวมจุดลอยตัวที่แม่นยำของค่าใน iterablesqrt(x): คืนรากที่สองของ xexp(x): คืนค่า e^xlog(x[, base]): คืนลอการิทึมของ x ตามฐานที่กำหนด (ค่าเริ่มต้นคือ e)log10(x): คืนลอการิทึมฐาน 10 ของ xpow(x, y): คืน x ยกกำลัง y