列表[List] 元組(truple) 字典{dict} 生成器(generator) 帶有 yield 的函數在 Python 中被稱之為 generator(生成器) 迭代器 iterator 迭代器是訪問集合元素的一種方式。迭代器對象從集合的第一個元素開始訪問,直到所有的元素被訪問完結束。迭代 ...
- 列表[List] 元組(truple) 字典{dict}
# 列表中的每個元素都分配一個數字 - 它的位置,或索引,第一個索引是0,第二個索引是1,依此類推
# list comprehension
[i for i in range(10)]
# 元組與列表類似,不同之處在於元組的元素不能修改
# truple generator
(i for i in range(10))
# 字典的每個鍵值 key=>value 對用冒號 : 分割,每個鍵值對之間用逗號 , 分割,整個字典包括在花括弧 {} 中
# dict comprehension
{k:1 for k in range(10)}
- 生成器(generator)
帶有 yield 的函數在 Python 中被稱之為 generator(生成器)
def my_range(n):
i = 0
while i != n:
i += 1
yield i
r = my_range(10)
for i in r:
print(i)
- 迭代器 iterator
- 迭代器是訪問集合元素的一種方式。迭代器對象從集合的第一個元素開始訪問,直到所有的元素被訪問完結束。迭代器只能往前不會後退
while True:
try:
i = next(iter_obj)
except StopIteration:
break
class Pow2(object):
def __init__(self, max):
self.max = max
self.n = 0
def __iter__(self):
self.n = 0
return self
def __next__(self):
if self.n < self.max:
self.n += 1
return 2 ** self.n
else:
raise StopIteration
p = Pow2(10)
for i in p:
print(i)
- 實例方法(instance method), 類方法(class method), 靜態方法(static method)
# instance method
a = A() a.foo() a.bar()
# class method bind class
# static method
class A(object):
@staticmethod
def s_foo():
pass
@classmethod
def c_foo(cls):
pass
def foo(self):
pass
a = A()
a.foo()
A.c_foo()
- 深拷貝 淺拷貝
# 深拷貝
from copy import deepcopy
l1 = []
l2 = deepcopy(l1)
l1.append(1)
print(l2)
# 淺拷貝
l1 = [1, [1, 2], 3]
l2 = l1[:]
def foo(a=[]):
a.append(1)
print(a)
foo()
foo()
- lambda表達式, 閉包(closure)
- lambda
import functools import operator mul2 = lambda x: 2 * x print(mul2(3)) print(list(map(lambda x: 3 * x, [1, 2, 3, 4]))) print(list(filter(lambda x: x % 3 == 0, [1, 2, 3, 4]))) print(functools.reduce(operator.add, [1, 2, 3, 4, 5], 5))
- closure
# 例子一 def greeting(msg): def hello(name): print(msg, name) return hello h = greeting("welcome") h("akira") # 例子二 l = [] for i in range(10): def _(i=i): print(i) l.append(_) for f in l: f()
- *args, **kwargs
args獲取tuple, kwargs獲取kwargs
def log(*args, **kwargs):
print("args", args)
print("kwargs", kwargs)
log(1, 2, 3, 4)
log(1, 2, [1, 2, 3], c=4)
- 遞推式構造列表
# list comprehension
r1 = [i for i in range(10)]
print(r1)
# dict comprehension
r2 = {k:1 for k in range(10)}
print(r2)
# list generator
r3 = (i for i in range(10))
print(list(r3))
- 裝飾器(decorator)
可用於AOP(aspect oriential programming)
例如:
if debug:
xxx
else:
yyy
decorator例子
def simple_wrapper(fn):
def _():
#print(fn.__name__)
return fn()
return _
def fix_arg_wrapper(fn):
def _(x):
#print(fn.__name__)
return fn(x)
return _
def all_args_wrapper(fn):
def _(*args, **kwargs):
print(*args, **kwargs)
return fn(*args, **kwargs)
return _
@simple_wrapper
def foo():
pass
@all_args_wrapper
def bar(a, b, c):
pass
foo()
bar(1, 2, 3)
- 魔法方法(magic method)
形如:
__xxx__
例子:
class LogAll(object):
def __init__(self):
self.a = 1
self.b = 2
self.c = 3
def __getattribute__(self, item):
print(item)
l = LogAll()
print(l.a)
l.a = 1
l.b
l.c
class Any(object):
def __getattr__(self, item):
print(item)
def __setattr__(self, key, value):
print("set", key, value)
a = Any()
a.a
a.a = 1
class Any2(object):
def __getattr__(self, item):
def _(*args, **kwargs):
print("function name", item)
print("args", args)
print("kwargs", kwargs)
setattr(self, item, _)
return _
a = Any2()
a.a1(1, 2, 3)
a.a2(1, 2, [1, 2, 3], c=[])
- Mixin模式
例子:
class A(object):
def foo(self):
print("foo")
def bar(self):
print("bar")
self.shit()
class B(object):
def shit(self):
print("shit")
class C(A, B):
pass
c = C()
c.bar()
- 字元串反轉
new_x = str_x[::-1]
- 關於i++
python 中的沒有 i++ ,如果寫了會報語法錯誤。
但是python 中有 --i,++i,+-i,-+i,他們不是實現-1操作的,僅僅是作為判斷運算符號,類似數學中的負負得正
i = 2
print ++i //2
print -+i //-2
print +-i //-2
print --i //2
邏輯表達式
python 中沒有 && ,!, || 這3個運算符,在邏輯表達式中寫成這3個會抱邏輯錯誤的。要實現同樣的功能,要寫成 and,not,or
返回值 2 and 3 返回3
返回值 2 or 3 返回2
返回值 not 2 and 3 返回 False- if-elif-else的寫法
例如:比較兩個二叉樹是否相同
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSameTree(self, p: 'TreeNode', q: 'TreeNode') -> 'bool':
if p is None and q is None:
return True
elif p is not None and q is not None:
if p.val == q.val:
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
else:
return False
else:
return False
- 其它
top_element = stack.pop() if stack else '#'
相當於
if stack:
top_element = stack.pop()
else:
top_element = '#'