可點進來看看的一些Python基礎

1.
判斷類型除了用 type(L) 
推薦使用 isinstance(L, list)


2.
將 x 十進制數轉換爲十六進制,八進制,二進制
hex(x) oct(x) bin(x)
表示爲字符串


3.
x in y,x not in y 成員對象測試
x is y,x is not y 對象實體測試
1 < a < 3 可連續比較


4.
// 取整除 - 返回商的整數部分
9//2 輸出結果 4 , 9.0//2.0 輸出結果 4.0


5.
int(3.4), float(3) 強制類型轉換


6.
Decimal 模塊:小數模塊
Decimal("0.01")
decimal.getcontext().prec = 4 設置全局精度爲 4,小數點後 4 位


Fraction 模塊:分數模塊
Fraction(4, 6) 4/6
可接收字符串類型的參數 Fraction("0.25") 1/4


7.
set :無序,不重複元素集
s1.union(s2) 並集
s1.intersection(s2) 交集
s1.difference(s2) 差集
s1,stmmetric_difference(s2) 在 s1 或者 s2 中,但不會同時出現在二者中
s.add('x')  s.remove('X') 增加刪除
s.update([x,x,x])  更新
x in s, x not in s 存在某值
{x**2 for x in [1,2,3,4]} {16,1,4,9} 集合解析,無序
{x for x in 'span'} {'a','p','s','n'} 集合解析,無序
set 是可變對象,即不存在 hash 值,不能作爲字典的鍵值


8.
frozenset :沒有 add,remove 等方法
s = set([1,1,1])
x = set()
x.add(s)  error:set 是不可哈希類型
x.add(frozenset(s)) 


9.
布爾類型 bool:
type(bool) 返回 <class 'bool'>
isinstance(False, int) bool類型屬於整形,所以返回True
True == 1 True
True is l False


10.
變量名通過引用,指向對象
L = [1], M = [1] , L is M False
L = M = [1] , L is M True
L = L + [2,3]  # L = [1,2,3] M = [1]
L += [2,3] # L = [1,2,3] M = [1,2,3]
普通 + 對此對象進行修改成新的對象
增強賦值 += 會找到對象的起始點進行修改


11.
字符串操作:s1 + s2, s1 * 3, s[i], s[i:j], len(s) 
字符串格式化表達式:'xxx %s yyy' % 'kind'
字符串格式化方法: 'x {1} {0} b'.format('c', 'v')
字符串迭代:
>>> s = "zhaoyi"
>>> for x in s: print (x)
... 
z
h
a
o
y
i
字符串列表解析:
>>> print [y * 2 for y in s]
['zz', 'hh', 'aa', 'oo', 'yy', 'ii']
字符串輸出:
>>> print ','.join(['a','b','c'])
a,b,c


12.
部分內置函數 str 功能:
首字母大寫:capitalize()
每個單詞首字母大寫:title()


13.
""" 編寫多行字符串,並自己引入\n
temp = """ fdsfdsfs
dsada
 dsadsfs """
temp 是 fdsfdsfs\n dsada \n dsadsfs


14.
>>> S = [1,2,3,4,5,6,7,8,9,10,11,22]
>>> S[1:10:2]
[2, 4, 6, 8, 10]
>>> S[:-1]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> S[1:]
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 22]
>>> S[-1]
22
>>> S[0]
1
>>> 


15.
基於字典的格式化表達式
>>> print "%(n1)d---%(n2)s" % {"n1":11, "n2":"von"}
11---von


16.
a = [0,1,2,3,4,5,6,7]
del a[::2]
除去偶數項,a = [1,3,5,7]


17.
dict.update(dict_other) # 合併字典
dict.popitem() # 隨機的一項鍵值對
字典鍵不一定非得是字符串,也可以爲任何的不可變對象
字符串,整數,tuple都是不可變對象


18.
字典解析
>>> D = {k:8 for k in ['d','s']}
>>> D
{'s': 8, 'd': 8}
>>> z = {k:v for (k,v) in zip(['name', 'age'], ['tom', 12])}
>>> z
{'age': 12, 'name': 'tom'}


19.
元組和列表的唯一區別在於元組是不可變對象,列表是可變對象
不僅僅是長度不可變,元素也是不可變的


20.
元組的逗號和圓括號
>>> d = (12)
>>> d
12
>>> d = (12,)
>>> d
(12,)


21.
通常意義下的類型分類:
1.數字、序列、映射
2.可變類型和不可變類型


22.
常見賦值的形式
>>> sm = 'sm'
>>> sm
'sm'
>>> sm, sw = 'spam', 'swap'
>>> sm
'spam'
>>> sw
'swap'
>>> [sm, sw] = ['s', 'h']
>>> sm
's'
>>> sw
'h'
>>> a, b, c, d = 'abcd'
>>> a
'a'
>>> b
'b'
>>> c
'c'
>>> d
'd'
>>> sm = se = 'hh'
>>> sm
'hh'
>>> se
'hh'


Python3.x 有的序列解包形式
a, *b, c = 'sw'


23.
>>> 1 or 3 or 2
1
>>> 1 and 2 and 5
5
>>> 
and 或者 or 總是返回左邊的對象或者右邊的對象且具有短路求值的特性


24.
if/else 三元表達符
>>> x = 4
>>> a = 1 if x else 2
>>> a
1
>>> y = 0
>>> a = 1 if x else (2 if y else 3)
>>> a
1
>>> x = 0
>>> a = 1 if x else (2 if y else 3)
>>> a
3


也可用 and-or
>>> result = (a > 20 and "bigger than 20" or a > 10 and "bigger than 10")
>>> result
'bigger than 10'


25.
Python 的 while 語句或者 for 語句可以帶else,當然也可以帶 continue/break/pass
while a > 1:
lala
else:
hehe
for i in range(5):
lala
else:
hehe
else語句會在循環結束後執行


26.
>>> r = [a if a > 0 else 0 for a in [-1, 0, 1]]
>>> r
[0, 0, 1]
帶判斷條件的高級解析過程
>>> for a, b in zip(['A', 'A+'], ['B', 'B+']):
...  print (a + "vs" + b)
... 
AvsB
A+vsB+
>>> for index, data in enumerate(['a', 'b', 'c']):
...     print (index, data)
... 
(0, 'a')
(1, 'b')
(2, 'c')
enumerate 用處還是挺廣泛的


27.
命名慣例
以單一下劃線開頭的變量名(_X)不會被from module import*等語句導入
前後有兩個下劃線的變量名(__X__)是系統定義的變量名,對解釋器有特殊意義
以兩個下劃線開頭但不以下劃線結尾的變量名(__X)是類的本地(私有)變量


28.
手動迭代
>>> L = [1,2,3]
>>> i = iter(L)
>>> i.next()
1
>>> i.next()
2
>>> i.next()
3
>>> i.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration


29.
函數參數 * 和 ** 使用
>>> def f(a, *b, **c):
...     print (a,b,c)
... 
>>> f(1,2,3,x=4,y=5)
(1, (2, 3), {'y': 5, 'x': 4})


func(1, *(2, 3), **{'c':3, 'b':2})
等價於
func(1, 2, 3, b = 2, c = 3)


30.
瞭解 Lambda 的基本使用
>>> f1 = lambda x, y, z : x + y + z
>>> f1(1,2,3)
6
>>> f2 = lambda x = 1, y = 1 : x + y
>>> f2
<function <lambda> at 0x7fa2d68606e0>
>>> f2()
2
>>> list(map((lambda x: x+2), [1,2,3]))
[3, 4, 5]
>>> list(filter((lambda x: x>0), range(-4,5)))
[1, 2, 3, 4]
>>> reduce((lambda x, y: x + y), [1, 2, 3])
6


31.
生成器函數 yield
>>> def gen(N):
...     for i in range(N):
...             yield i ** 2
... 
>>> for i in gen(5):
...     print(i)
... 
0
1
4
9
16
>>> x = gen(2)
>>> next(x)
0
>>> next(x)
1
>>> next(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
如果說上面用的是 return,那麼最終只會返回一個值,並不能達到展示過程的目的,而 yield 可以將狀態掛起,恢復到那一時刻的狀態


32.
生成器表達式 小括號進行列表解析
>>> g = (x ** 2 for x in range(3))
>>> next(g)
0
>>> next(g)
1
>>> next(g)
4
>>> next(g)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
生成器是單個迭代對象
>>> gen = (i for i in range(4))
>>> 2 in gen
True
>>> 3 in gen
True
>>> 1 in gen
False
生成器不保留迭代後的結果,檢測2的時候,1已經跳過去不在了,同理2,3也不在了


33.
函數的默認值,我認爲,可變的類型,參數在實例化是變化的,不可變的類型,在實例化是不可變的
>>> def foo(number=[]):
...     number.append(3)
...     print (number)
... 
>>> foo()
[3]
>>> foo()
[3, 3]
>>> foo()
[3, 3, 3]
改進
>>> def foo(number=None):
...     if number is None:
...             number = []
...     number.append(33)
...     print (number)
... 
>>> foo()
[33]
>>> foo()
[33]
>>> foo()
[33]
數字爲參數,數字不可變
>>> def foo(count=1):
...     count += 1
...     print (count)
... 
>>> foo()
2
>>> foo()
2
>>> foo(4)
5
>>> foo(4)
5
>>> foo()
2


34.
Python中的多維數組
>>> lists = [0]*3
>>> lists
[0, 0, 0]
>>> lists = [[]] * 3
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]
>>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists[1].append(4)
>>> lists[2].append(5)
>>> lists
[[3], [4], [5]]
>>> lists = [[[] for j in range(4)] for i in range(3)]  # 3行4列


35.
import sys
sys.stdout # 是類文件對象,但是它們都只寫,write()
sys.stdout.write("XXXX")


36.
包相對導入
from . import spam # 導入當前目錄下的 spam 模塊(錯誤:當前目錄下的模塊,直接導入即可)
from .spam import name # 導入當前目錄下的 spam 模塊的 name 屬性(錯誤: 一定要加 . ,當前目錄下的模塊,不是直接導入)
from .. import spam # 導入當前目錄的父目錄下的 spam 


37.
Python 的類沒有基於參數的函數重載
class temp:
  def test(self, string):
print (string)
  def test(self):
print ("hi")
後者 test 會覆蓋前者


38.
class A(B):
  pass
a = A()
isinstance(a,B) # True ,A 是 B 的子類


39.
包裝對象,委託 __getattr__ 鉤子方法實現的,攔截對不存在屬性的讀取
class wrapper:
  def __init__(self, object):
self.wrapper = object
def __getattr(self, attrname):
print ('Trace:', attrname)
return getattr(self.wrapped, attrname)
getattr(X, N) 內置函數以變量名字字符串 N 從包裝對象 X 中取出屬性,類似於 X.__dict[N]
x = wrapper([1,2,3])
x.append(4)
"Trace: append" [1,2,3,4]
-----------------------------
x = wrapper({'a': 1, 'b': 2})
list(x.keys())
"Trace: keys" ['a', 'b']


40.
__attr 是類的僞私有屬性
本面貌爲: self._class.__attr = xxx 來改變


41.
動態語言靈活性
可給一個 class 的實例,繼續添加屬性和方法,使用 MethodType
c = Class()
c.new_method = MethodType(new_method, c) # 給實例加方法,類的其他實例不受影響


Class.new_method = MethodType(new_method, Student) # 給類綁定一個方法,所有實例共有


42.
函數裝飾器
@staticmethod
def smeth(x):
  print x
等價於
def smeth(x):
  print x
smeth = staticmethod(smeth)
一般都爲內置函數吧


43.
類修飾器
def dec(XXX):
pass


@dec
class C:
pass
等價於
class C:
pass
C = dec(C)


44.
class sss:
__slots__('1', '2')# 可列表可元組
限制只有1,2兩個屬性
只對當前類起作用,子類不起作用
發佈了235 篇原創文章 · 獲贊 27 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章