1、python中有一些類似數學集合的運算,如 或、且、非的關係,對應的運算符有 |,&,-等運算符。這些運算符都是僅限於集合set的操作,也有一定的實用性。
# 創建兩個集合x, y
>>> x = set('spam')
>>> y = {'h', 'a', 'm'}
>>> x, y
({'a', 'p', 'm', 's'}, {'h', 'm', 'a'})
# 對集合求交集,獲取兩個集合共有數據
>>> x & y
{'a', 'm'}
# 對集合求併集,獲取兩個集合擁有的數據
>>> x | y
{'a', 'p', 'm', 's', 'h'}
# 對集合做差
>>> x - y
{'p', 's'}
>>> {x ** 2 for x in [1, 2, 3, 4]}
{16, 1, 4, 9}
需要注意的是此處只能針對集合做操作,換成列表是不行的。
>>> x = list(x)
>>> x
['a', 'p', 'm', 's']
>>> y = list(y)
>>> y
['h', 'm', 'a']
# 此處報錯,直接說明類型不支持
>>> x | y
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
x | y
TypeError: unsupported operand type(s) for |: 'list' and 'list'
>>> x & y
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
x & y
TypeError: unsupported operand type(s) for &: 'list' and 'list'
2、使用decimal模塊控制浮點數精度
(1)使用round函數的一個小弊端
>>> round(3.22, 1)
3.2
# 當使用round函數保留兩位小數時,
# 由於最後一位是0,所以被捨棄,最後僅
# 保留了一位小數,3.20也就成了3.2
>>> round(3.203, 2)
3.2
(2)使用decimal模塊解決上述問題
>>> import decimal
# 構建decimal對象時,注意此處傳參必須是字符
# 如何是小數,還是會出現精度問題
>>> deci = decimal.Decimal('3.20')
# 使用quantize方法,構造精度,此處是小數點後保留兩位
# 返回對象依舊為decimal對象
>>> res = deci.quantize(decimal.Decimal('0.00'))
>>> res
Decimal('3.20')
# 獲取字符
>>> res.to_eng_string()
'3.20'
哈哈,以上就是Python小工具關於數學中的一些運算,有興趣歡迎關注python小工具。