阿里天池Python訓練營 task 1

2020-09-23 14:00:18

1.位運算

例:對4進行按位元取反

print(bin(~4),~4)
#執行結果
-0b101 -5

計算過程:若按16位元進行計算,先將4轉換成二進位制:0000 0000 0000 0100,對它每一位取反得到最終結果的二補數:1111 1111 1111 1011,再根據二補數來得到原碼為:1000 0000 0000 0101,轉換為十進位制就是-5。

2.資料型別與轉換

2.1使用getcontext().prec調整精度

例:使1/3保留四位。

import decimal
from decimal import Decimal
decimal.getcontext().prec=4
c=Decimal(1)/Decimal(3)
print(c)
#執行結果
0.3333

2.2isinstance(object,classinfo)

object – 範例物件。
classinfo – 可以是直接或間接類名、基本型別或者由它們組成的元組。判斷一個物件是否是為已知型別。

print(isinstance(2, int))
print(isinstance(5.7, float))
print(isinstance(True, bool))
print(isinstance('5.22', str))
#執行結果
True True True True

isinstance()type() 區別:

type() 不會認為子類是一種父類別型別,不考慮繼承關係。

isinstance() 會認為子類是一種父類別型別,考慮繼承關係。

如果要判斷兩個型別是否相同推薦使用 isinstance()
例:

class A:
    pass
 
class B(A):
    pass
 
print(isinstance(A(), A))    #True
print(type(A()) == A)        #True
print(isinstance(B(), A))    #True
print(type(B()) == A)        #False

3.迴圈語句

3.1while-else迴圈

while 布林表示式:
	程式碼塊
else:
	程式碼塊

while 迴圈正常執行完的情況下,執行 else 輸出,如果 while 迴圈中執行了跳出迴圈的語句,比如 break ,將不執行 else 程式碼塊的內容。
例:

count = 0
while count < 2:
	print("%d is  less than 2" % count)
	count = count + 1
	#break可直接跳出迴圈,不執行else語句
else:
	print("%d is not less than 2" % count)
	
# 0 is  less than 2
# 1 is  less than 2
# 2 is not less than 2

3.2enumerate()函數

enumerate() 函數用於將一個可遍歷的資料物件(如列表、元組或字串)組合為一個索引序列,同時列出資料和資料下標,一般用在 for 迴圈當中。

enumerate(sequence, [start=0])
sequence – 一個序列、迭代器或其他支援迭代物件。
start – 下標起始位置。

例:

>>>seasons = ['Spring', 'Summer', 'Autumn', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Autumn'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))       # 下標從 1 開始
[(1, 'Spring'), (2, 'Summer'), (3, 'Autumn'), (4, 'Winter')]

普通的for迴圈

>>>i = 0
>>> seq = ['one', 'two', 'three']
>>> for element in seq:
	    print i, seq[i]
     	i +=1

0 one
1 two
2 three

for迴圈使用enumerate()

>>>seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
...     print i, element
... 
0 one
1 two
2 three

4.推導式

4.1列表推導式

列表推導式格式:

[ expr for value in collection [if condition]

例:

x = [-4, -2, 0, 2, 4]
y = [a * 2 for a in x]
print(y) 

#[-8, -4, 0, 4, 8]

x = [[i, j] for i in range(0, 3) for j in range(0, 3)]
print(x)

# [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]

a = [(i, j) for i in range(0, 3) if i < 1 for j in range(0, 3) if j > 1]
print(a)

# [(0, 2)]

4.2元組推導式

元組推導式格式:

(expr for value in collection [if condition])

例:

a=tuple(x for x in range(10))
print(a)

#(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

4.3字典推導式

元組推導式格式:

{ key_expr: value_expr for value in collection [if condition] }

例:

b = {i: i % 2 == 0 for i in range(10) if i % 3 == 0}
print(b)

# {0: True, 3: False, 6: True, 9: False}

4.4集合推導式

元組推導式格式:

{ expr for value in collection [if condition]

例:

c = {i for i in [1, 2, 3, 4, 5, 5, 6, 4, 3, 2, 1]}
print(c)

# {1, 2, 3, 4, 5, 6}

4.5next()函數

next() 返回迭代器的下一個專案。
next() 函數要和生成迭代器的iter() 函數一起使用。
語法:

next(iterable[, default])

iterable – 可迭代物件
default – 可選,用於設定在沒有下一個元素時返回該預設值,如果不設定,又沒有下一個元素則會觸發 StopIteration 異常。

例:

# 首先獲得Iterator物件:
it = iter([1, 2, 3, 4, 5])
# 迴圈:
while True:
    try:
        # 獲得下一個值:
        x = next(it)
        print(x)
    except StopIteration:
        # 遇到StopIteration就退出迴圈
        break
        
#1 2 3 4 5

5.例外處理

5.1try-except語句

格式:

try:
	檢測範圍 
except Exception[as reason]:
	出現異常後的處理程式碼

工作方式:

  1. 首先,執行 try 子句(在關鍵字 try 和關鍵字 except 之間的語句
  2. 如果沒有異常發生,忽略 except 子句, try 子句執行後結束。
  3. 如果在執行 try 子句的過程中發生了異常,那麼 try 子句餘下的部分將被忽略。如果異常的型別和 except 之後的名稱相符,那麼對應的 except 子句將被執行。最後執行 try - except 語句之後的程式碼
  4. 如果一個異常沒有與任何的 except 匹配,那麼這個異常將會傳遞給上層的 try 中。

例:

try:
	f = open('test.txt')
	print(f.read())
	f.close()
except OSError:
	print('開啟檔案出錯')
	
# 開啟檔案出錯

一個 try 語句可能包含多個 except 子句,分別來處理不同的特定的異常。最多隻有一個分支會被執行。
例:

dict1 = {'a': 1, 'b': 2, 'v': 22} 
try:
	x = dict1['y']
except LookupError:
   	print('查詢錯誤')
except KeyError:
   	print('鍵錯誤') 
else:
	print(x)
	
# 查詢錯誤

try-except-else 語句嘗試查詢不在 dict 中的鍵值對,從而引發了異常。這一異常準確地說應屬 於 KeyError ,但由於 KeyErrorLookupError 的子類,且將 LookupError 置於 KeyError 之前,因此程式 優先執行該 except 程式碼塊。所以,使用多個 except 程式碼塊時,必須堅持對其規範排序,要從最具針對性的異常到最通用的異常。

一個 except 子句可以同時處理多個異常,這些異常將被放在一個括號裡成為一個元組。
例:

try:
	...
except (OSError, TypeError, ValueError) as error:
	print('出錯了!\n原因是:' + str(error))
	
# 出錯了! 
# 原因是:unsupported operand type(s) for +: 'int' and 'str'

5.2try-except-finally語句

格式:

try:
	檢測範圍
except Exception[as reason]:
	出現異常後的處理程式碼
finally:
	無論如何都會被執行的程式碼

不管 try 子句裡面有沒有發生異常, finally 子句都會執行。

5.3try-except-else語句

格式:

try:
	檢測範圍 
except:
	出現異常後的處理程式碼 
else:
	如果沒有異常執行這塊程式碼

使用 except 而不帶任何異常型別,這不是一個很好的方式,我們不能通過該程式識別出具體的異常資訊,因為它捕獲所有的異常。

5.4raise語句

使用 raise 語句丟擲一個指定的異常。
例:

try:   
	raise NameError('HiThere') 
except NameError: 
	print('An exception flew by!')
	
# An exception flew by!