Python常用數字處理基本操作匯總
一些基本的操作,在工作者遇到相關問題要有相關印象。
一、 你想對浮點數執行指定精度的舍入運算
對于簡單的舍入運算,使用內置的 round(value, ndigits) 函數即可。比如:
>>> round(1.23, 1)1.2>>> round(1.27, 1)1.3>>> round(-1.27, 1)-1.3>>> round(1.25361,3)1.254>>>
當一個值剛好在兩個邊界的中間的時候, round 函數返回離它最近的偶數。 也就是說,對1.5或者2.5的舍入運算都會得到2。
傳給 round() 函數的 ndigits 參數可以是負數,這種情況下, 舍入運算會作用在十位、百位、千位等上面。比如:
>>> a = 1627731>>> round(a, -1)1627730>>> round(a, -2)1627700>>> round(a, -3)1628000>>>
不要將舍入和格式化輸出搞混淆了。 如果你的目的只是簡單的輸出一定寬度的數,你不需要使用 round() 函數。 而僅僅只需要在格式化的時候指定精度即可。比如:
>>> x = 1.23456>>> format(x, ’0.2f’)’1.23’>>> format(x, ’0.3f’)’1.235’>>> ’value is {:0.3f}’.format(x)’value is 1.235’>>>
二、進制轉化
為了將整數轉換為二進制、八進制或十六進制的文本串, 可以分別使用 bin() , oct() 或 hex()函數:
>>> x = 1234>>> bin(x)’0b10011010010’>>> oct(x)’0o2322’>>> hex(x)’0x4d2’>>>
為了以不同的進制轉換整數字符串,簡單的使用帶有進制的 int() 函數即可:
>>> int(’4d2’, 16)1234>>> int(’10011010010’, 2)1234>>>
三、分數相關運算
>>> from fractions import Fraction>>> a = Fraction(5, 4)>>> b = Fraction(7, 16)>>> print(a + b)27/16>>> print(a * b)35/64
>>> # Getting numerator/denominator>>> c = a * b>>> c.numerator35>>> c.denominator64
>>> # Converting to a float>>> float(c)0.546875
>>> # Limiting the denominator of a value>>> print(c.limit_denominator(8))4/7
>>> # Converting a float to a fraction>>> x = 3.75>>> y = Fraction(*x.as_integer_ratio())>>> yFraction(15, 4)>>>
四、random模塊
random 模塊有大量的函數用來產生隨機數和隨機選擇元素。 比如,要想從一個序列中隨機的抽取一個元素,可以使用 random.choice() :
>>> import random>>> values = [1, 2, 3, 4, 5, 6]>>> random.choice(values)2>>> random.choice(values)3>>> random.choice(values)1>>> random.choice(values)4>>> random.choice(values)6>>>
為了提取出N個不同元素的樣本用來做進一步的操作,可以使用 random.sample() :
>>> random.sample(values, 2)[6, 2]>>> random.sample(values, 2)[4, 3]>>> random.sample(values, 3)[4, 3, 1]>>> random.sample(values, 3)[5, 4, 1]>>>
如果你僅僅只是想打亂序列中元素的順序,可以使用 random.shuffle() :
>>> random.shuffle(values)>>> values[2, 4, 6, 5, 3, 1]>>> random.shuffle(values)>>> values[3, 5, 2, 1, 6, 4]>>>
生成隨機整數,請使用 random.randint() :
>>> random.randint(0,10)2>>> random.randint(0,10)5>>> random.randint(0,10)0>>> random.randint(0,10)7>>> random.randint(0,10)10>>> random.randint(0,10)3>>>
為了生成0到1范圍內均勻分布的浮點數,使用 random.random() :
>>> random.random()0.9406677561675867>>> random.random()0.133129581343897>>> random.random()0.4144991136919316>>>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: