awesome python 中文大全
Fabric , pip, virtualenv
內建函數好文
awesome pythonhtml
from functools import reduce reduce(lambda x, y: x * y, range(1,int(input('number:'))+1), 1) # 遞歸 def factorial(n): return 1 if n<=1 else n*factorial(n-1) factorial = lambda x: 1 if x<=1 else x*factorial(x-1) factorial(6)
from functools import reduce print('\n'.join(map(lambda x: '{0:{1}<9}{0}{0:{1}>9}'.format(*('|','') if x%5 else ('+','-')),range(11))))
''.join([ chr(i) for i in range(97,123)]) import string string.ascii_lowercase
# 排列 from itertools import permutations a = [1,2,3] b = permutations(a) print(list(b)) # 組合 from itertools import combinations for tuple_1 in [ i for i in combinations('abc', 2)]: print(tuple_1)
words = ['apple','bat','bar','atom','book'] by_letter_grp_dict = {} for word in words: letter = word[0] if letter in by_letter_grp_dict: by_letter_grp_dict[letter].append(word) else: by_letter_grp_dict[letter] = [word] print(by_letter_grp_dict)
內置的collections模塊有一個叫作defaultdict的類,它可使該過程更簡單。傳入一個類型或函數(用於生成字典各插槽所使用的默認值)便可建立一個defaultdict: words = ['apple','bat','bar','atom','book'] from collections import defaultdict by_letter = defaultdict(list) for word in words: by_letter[word[0]].append(word) print by_letter #defaultdict(<type 'list'>, {'a': ['apple', 'atom'], 'b': ['bat', 'bar', 'book']})
>>> from collections import Counter >>> c = Counter('hello world!') >>> c Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1, '!': 1}) >>> c.most_common(1) [('l', 3)] >>> c.most_common(3) [('l', 3), ('o', 2), ('h', 1)] >>>
>>> a = [1,2,3,4,5,6] >>> b,*c,d,e = a >>> b 1 >>> c [2, 3, 4] >>> d 5 >>> e 6
crash = dict(zip(range(10 **0xA), range(10 **0xA)))
>>> import collections >>> Card = collections.namedtuple('Card',['rank','suit']) >>> class French_Deck(object): ... rank = [ str(i) for i in range(2,11,1)] + list('JQKA') ... suit = 'Spade,Club,Heart,Diamond'.split(',') ... def __init__(self): ... self._cards = [Card(r,s) for s in suit for r in rank] ... def __getitem__(self,position): ... return self._cards[position] ... def __len__(self): ... return len(self._cards) ... >>> cards = French_Deck() >>> len(cards) 56 from collections import namedtuple stock_list = [['AAPL','10.30','11.90'],['YAHO','9.23','8.19'],['SINA','22.80','25.80']] stock_info = namedtuple('stock_info',['name','start','end']) [stock_info(name,start,end) for name,start,end in stock_list ] stock_list # 與 update 不同哦。。。 from collections import ChainMap dict_1 = {'name':'Frank','age':18} dict_2 = {'name':'','age':20} dict_coalesce = ChainMap(dict_1,dict_2) dict_coalesce['name']
#把列表分割成一樣大小的塊? a = [1, 2, 3, 4, 5, 6] list(zip( *[iter(a)]*2 )) >>> [(1, 2), (3, 4), (5, 6)]
def chunks(l, n): return [l[i:i+n] for i in range(0, len(l), n)] chunks(s,2)
d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} def my_dict2obj(args): class obj(object): def __init__(self,d): for key,value in d.items(): if not isinstance(value,(list,tuple)): setattr(self,key,obj(value) if isinstance(value,dict) else value) else: setattr(self,key,[obj(i) if isinstance(i,dict) else i for i in value]) return obj(args) x = my_dict2obj(d) print(x.d)
# 合併list相鄰項 a = [1, 2, 3, 4, 5, 6] list(zip( a[::2], a[1::2] )) >>> [(1, 2), (3, 4), (5, 6)]
# 合併字符串以及反序字符串 >>> s = ['a','b','c','d','e','f','g','h'] >>> ''.join(s) 'abcdefgh' >>> ''.join(s[::-1]) 'hgfedcba'
# 隨機生成 5 個包含數字和字母的 >>> import random >>> import string >>> (random.choice(string.ascii_uppercase+string.digits) for _ in range(5)) <generator object <genexpr> at 0x03A0FEA0> >>> for i in (random.choice(string.ascii_uppercase+string.digits) for _ in range(5)) : ... print(i) ... K 8 E V 0
python 庫大全python
def read_file(fpath): BLOCK_SIZE = 1024 with open(fpath, 'rb') as f: while True: block = f.read(BLOCK_SIZE) if block: yield block else: return
In [35]: def groupby(items, size): ....: return zip(*[iter(items)]*size) ....: In [36]: groupby(range(9), 3) Out[36]: [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
# 定義 Field 全部字段類的父類 class Field(object): def __init__(self,name,column_type): self.name = name self.column_type = column_type class StringField(Field): def __init__(self,name): # 此處的 StringField 是 type , self 是構造方法中調用必須傳遞的參數,就是規定! return super(StringField,self).__init__(name,'varchar(100)') class IntegerField(Field): def __init__(self,name): # 與上面 StringField 對應註釋同理 return super(IntegerField,self).__init__(name,'bigint') # 定義Model 及其子類的 元類 必須繼承自 type,用於拼接動態sql 作 ORM 映射,沒什麼難的 class ModelMetaclass(type): def __new__(cls,name,bases,attr_dict): # 排除 Model 本身自己,只對它的子類進行映射 if(name == 'Model'): return type.__new__(cls,name,bases,attr_dict) print('Found Model {}'.format(name)) # 開始對子類進行屬性與字段綁定 mappings = dict() for key,value in attr_dict.items(): # 判斷爲 Field 類型的,就儲存起來綁定 if isinstance(value,Field): print('Found Field => {}'.format(key)) mappings[key] = value # 爲了防止 attrs_dict 中的實例屬性覆蓋類的屬性,出棧這部分 for key in mappings.keys(): attr_dict.pop(key) print('出棧實例屬性 => {}'.format(key)) # 開始綁定 類屬性與表中的字段 ,整個這麼多工做只是爲了下面兩個綁定!!! attr_dict['__mappings__'] = mappings attr_dict['__table__'] = name # 返回建立的心的對象 return type.__new__(cls,name,bases,attr_dict) # 開始定義咱們的 Model 類 繼承自 dict 的緣由? 思索,應該是調用它的dict[key] 方法, 關鍵在於 save 方法,如何從 mappings 中取出字符串而且拼接成 sql的 class Model(dict,metaclass = ModelMetaclass): ## 構造方法接收的是一個 屬性字典集合 name='Tome',age=18,job='developer' 這種形式 def __init__(self,**kw): super(Model,self).__init__(**kw) # 獲取屬性值方法 def __getattr__(self,key): return self[key] # 看此處 dict 的取值方法多方便 # 設置屬性值方法 def __setattr__(self,key,value): self[key] = value def __replace__placeholder__(self,str_hold_placeholder,replace_str): args_str = '' j = 0 for i,v in enumerate(str_hold_placeholder): s = v if v == '?': s = str(replace_str[j]) j = j+1 args_str = args_str + s return args_str # 拼接動態sql並保存到數據庫中 def save(self): fields=[] args = [] params = [] table_name = self.__table__ for attr_key,attr_value in self.__mappings__.items(): fields.append(attr_key) args.append(getattr(self,attr_key)) params.append('?') dynamic_sql = 'insert into {}({}) values({})'.format(table_name,','.join(fields),','.join(params)) print(dynamic_sql) print('args: {}'.format(args)) #封裝替換佔位符的方法 print(self.__replace__placeholder__(dynamic_sql,args)) # args_str = '' # j = 0 # for i,v in enumerate(dynamic_sql): # s = v # if v == '?': # s = str(args[j]) # j = j+1 # args_str = args_str + s # print('args_str: ',args_str) class User(Model): # 定義類的屬性到列的映射: id = IntegerField('id') name = StringField('username') email = StringField('email') password = StringField('password') # 開始測試...... # 建立一個實例: u = User(id=12345, name='Michael', email='test@orm.org', password='my-pwd') # 保存到數據庫: u.save() 輸出結果以下: Found Model User Found Field => id Found Field => email Found Field => name Found Field => password 出棧實例屬性 => password 出棧實例屬性 => name 出棧實例屬性 => id 出棧實例屬性 => email insert into User(password,name,id,email) values(?,?,?,?) args: ['my-pwd', 'Michael', 12345, 'test@orm.org'] insert into User(password,name,id,email) values(my-pwd,Michael,12345,test@orm.org)
from types import FunctionType from byteplay import Code, opmap def MetaClassFactory(function): class MetaClass(type): def __new__(meta, classname, bases, classDict): for attributeName, attribute in classDict.items(): if type(attribute) == FunctionType: attribute = function(attribute) newClassDict[attributeName] = attribute return type.__new__(meta, classname, bases, classDict) return MetaClass def _transmute(opcode, arg): if ((opcode == opmap['LOAD_GLOBAL']) and (arg == 'self')): return opmap['LOAD_FAST'], arg return opcode, arg def selfless(function): code = Code.from_code(function.func_code) code.args = tuple(['self'] + list(code.args)) code.code = [_transmute(op, arg) for op, arg in code.code] function.func_code = code.to_code() return function Selfless = MetaClassFactory(selfless) class Test(object): __metaclass__ = Selfless def __init__(x=None): self.x = x def getX(): return self.x def setX(x): self.x = x test = Test() print(test.getX()) test.setX(7) print(test.getX())
----------------------===============補充=====================-------------------git
題目:
array = [1, 8, 15]
g = (x for x in array if array.count(x) > 0)
array = [2, 8, 22]
Output:程序員
print(list(g))
[8]
問題:
爲何print 結果不是[1, 8, 15]呢??
解釋:
在生成式表達式中,in 語句是在聲明時進行評估的, 可是條件判斷是運行時才進行操做。
因此在運行前,array 被分配給列表[1, 8, 15], 而運行時array被分配給列表[2, 8, 22]
兩個不一樣時期列表中只有8是同時存在的,因此返回結果是8。github
35 個黑魔法?算法
一、拆箱
sql
二、拆箱變量交換數據庫
三、擴展拆箱(只兼容python3)編程
四、負數索引json
五、 切割列表
六、 負數索引切割列表
七、指定步長切割列表
八、負數步長切割列表
九、列表切割賦值
十、 命名列表切割方式
十一、列表以及迭代器的壓縮和解壓縮
關於怎麼快速學python,能夠加下小編的python學習羣:611+530+101,無論你是小白仍是大牛,小編我都歡迎,不按期分享乾貨
天天晚上20:00都會開直播給你們分享python學習知識和路線方法,羣裏會不按期更新最新的教程和學習方法,你們都是學習python的,或是轉行,或是大學生,還有工做中想提高本身能力的,若是你是正在學習python的小夥伴能夠加入學習。最後祝全部程序員都可以走上人生巔峯,讓代碼將夢想照進現實
十二、列表相鄰元素壓縮器
1三、在列表中用壓縮器和迭代器滑動取值窗口
1四、用壓縮器反轉字典
1五、列表展開
1六、 生成器表達式
1七、字典推導
1八、用字典推導反轉字典
1九、 命名元組
20、繼承命名元組
2一、操做集合
2二、操做多重集合
2三、統計在可迭代器中最常出現的元素
2四、 兩端均可操做的隊列
2五、有最大長度的雙端隊列
2六、可排序詞典
2七、默認詞典
2八、默認字典的簡單樹狀表達
2九、 對象到惟一計數的映射
30、最大和最小的幾個列表元素
3一、 兩個列表的笛卡爾積
3二、列表組合和列表元素替代組合
3三、列表元素排列組合
3四、可連接迭代器
3五、根據文件指定列類聚
顯示有限的接口到外部
當發佈python第三方package時, 並不但願代碼中全部的函數或者class能夠被外部import, 在__init__.py中添加__all__屬性,
該list中填寫能夠import的類或者函數名, 能夠起到限制的import的做用, 防止外部import其餘函數或者類
Python
from base import APIBase
from client import Client
from decorator import interface, export, stream
from server import Server
from storage import Storage
from util import (LogFormatter, disable_logging_to_stderr,
enable_logging_to_kids, info)
all = ['APIBase', 'Client', 'LogFormatter', 'Server',
'Storage', 'disable_logging_to_stderr', 'enable_logging_to_kids',
'export', 'info', 'interface', 'stream']
1
2
3
4
5
6
7
8
9
10
11
12
from base import APIBase
from client import Client
from decorator import interface, export, stream
from server import Server
from storage import Storage
from util import (LogFormatter, disable_logging_to_stderr,
enable_logging_to_kids, info)
all = ['APIBase', 'Client', 'LogFormatter', 'Server',
'Storage', 'disable_logging_to_stderr', 'enable_logging_to_kids',
'export', 'info', 'interface', 'stream']
with的魔力
with語句須要支持上下文管理協議的對象, 上下文管理協議包含 enter 和 exit 兩個方法. with語句創建運行時上下文須要經過這兩個方法執行進入和退出操做.
其中上下文表達式是跟在with以後的表達式, 該表示大返回一個上下文管理對象
Python
with open("test.txt", "r") as my_file: # 注意, 是__enter__()方法的返回值賦值給了my_file,
for line in my_file:
print line
1
2
3
4
with open("test.txt", "r") as my_file: # 注意, 是__enter__()方法的返回值賦值給了my_file,
for line in my_file:
print line
詳細原理能夠查看這篇文章《淺談 Python 的 with 語句》
知道具體原理, 咱們能夠自定義支持上下文管理協議的類, 類中實現 enter 和 exit 方法
Python
class MyWith(object):
def init(self):
print "init method"
def enter(self):
print "enter method"
return self # 返回對象給as後的變量
def exit(self, exc_type, exc_value, exc_traceback):
print "exit method"
if exc_traceback is None:
print "Exited without Exception"
return True
else:
print "Exited with Exception"
return False
def test_with():
with MyWith() as my_with:
print "running my_with"
print "------分割線-----"
with MyWith() as my_with:
print "running before Exception"
raise Exception
print "running after Exception"
if name == 'main':
test_with()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class MyWith(object):
def init(self):
print "init method"
def enter(self):
print "enter method"
return self # 返回對象給as後的變量
def exit(self, exc_type, exc_value, exc_traceback):
print "exit method"
if exc_traceback is None:
print "Exited without Exception"
return True
else:
print "Exited with Exception"
return False
def test_with():
with MyWith() as my_with:
print "running my_with"
print "------分割線-----"
with MyWith() as my_with:
print "running before Exception"
raise Exception
print "running after Exception"
if name == 'main':
test_with()
執行結果以下:
init method
enter method
running my_with
exit method
Exited without Exception
------分割線-----
init method
enter method
running before Exception
exit method
Exited with Exception
Traceback (most recent call last):
File "bin/python", line 34, in
exec(compile(__file__f.read(),
file, "exec"))
File "test_with.py", line 33, in
test_with()
File "test_with.py", line 28, in test_with
raise Exception
Exception
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
init method
enter method
running my_with
exit method
Exited without Exception
------分割線-----
init method
enter method
running before Exception
exit method
Exited with Exception
Traceback (most recent call last):
File "bin/python", line 34, in
exec(compile(__file__f.read(),
file, "exec"))
File "test_with.py", line 33, in
test_with()
File "test_with.py", line 28, in test_with
raise Exception
Exception
證實了會先執行
enter 方法, 而後調用with內的邏輯, 最後執行
exit 作退出處理, 而且, 即便出現異常也能正常退出
filter的用法
相對filter而言, map和reduce使用的會更頻繁一些, filter正如其名字, 按照某種規則過濾掉一些元素
Python
lst = [1, 2, 3, 4, 5, 6]
print filter(lambda x: x % 2 != 0, lst)
[1, 3, 5]
1
2
3
4
5
6
7
lst = [1, 2, 3, 4, 5, 6]
print filter(lambda x: x % 2 != 0, lst)
[1, 3, 5]
一行做判斷
當條件知足時, 返回的爲等號後面的變量, 不然返回else後語句
Python
lst = [1, 2, 3]
new_lst = lst[0] if lst is not None else None
print new_lst
1
1
2
3
4
5
lst = [1, 2, 3]
new_lst = lst[0] if lst is not None else None
print new_lst
1
裝飾器之單例
使用裝飾器實現簡單的單例模式
Python
def singleton(cls):
instances = dict() # 初始爲空
def _singleton(*args, **kwargs):
if cls not in instances: #若是不存在, 則建立並放入字典
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return _singleton
@singleton
class Test(object):
pass
if name == 'main':
t1 = Test()
t2 = Test()
# 二者具備相同的地址
print t1, t2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def singleton(cls):
instances = dict() # 初始爲空
def _singleton(*args, **kwargs):
if cls not in instances: #若是不存在, 則建立並放入字典
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return _singleton
@singleton
class Test(object):
pass
if name == 'main':
t1 = Test()
t2 = Test()
# 二者具備相同的地址
print t1, t2
staticmethod裝飾器
類中兩種經常使用的裝飾, 首先區分一下他們
普通成員函數, 其中第一個隱式參數爲對象
classmethod裝飾器, 類方法(給人感受很是相似於OC中的類方法), 其中第一個隱式參數爲類
staticmethod裝飾器, 沒有任何隱式參數. python中的靜態方法相似與C++中的靜態方法
Python
class A(object):
# 普通成員函數
def foo(self, x):
print "executing foo(%s, %s)" % (self, x)
@classmethod # 使用classmethod進行裝飾
def class_foo(cls, x):
print "executing class_foo(%s, %s)" % (cls, x)
@staticmethod # 使用staticmethod進行裝飾
def static_foo(x):
print "executing static_foo(%s)" % x
def test_three_method():
obj = A()
# 直接調用噗通的成員方法
obj.foo("para") # 此處obj對象做爲成員函數的隱式參數, 就是self
obj.class_foo("para") # 此處類做爲隱式參數被傳入, 就是cls
A.class_foo("para") #更直接的類方法調用
obj.static_foo("para") # 靜態方法並無任何隱式參數, 可是要經過對象或者類進行調用
A.static_foo("para")
if name == 'main':
test_three_method()
executing foo(<main.A object at 0x100ba4e10>, para)
executing class_foo(<class 'main.A'>, para)
executing class_foo(<class 'main.A'>, para)
executing static_foo(para)
executing static_foo(para)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class A(object):
# 普通成員函數
def foo(self, x):
print "executing foo(%s, %s)" % (self, x)
@classmethod # 使用classmethod進行裝飾
def class_foo(cls, x):
print "executing class_foo(%s, %s)" % (cls, x)
@staticmethod # 使用staticmethod進行裝飾
def static_foo(x):
print "executing static_foo(%s)" % x
def test_three_method():
obj = A()
# 直接調用噗通的成員方法
obj.foo("para") # 此處obj對象做爲成員函數的隱式參數, 就是self
obj.class_foo("para") # 此處類做爲隱式參數被傳入, 就是cls
A.class_foo("para") #更直接的類方法調用
obj.static_foo("para") # 靜態方法並無任何隱式參數, 可是要經過對象或者類進行調用
A.static_foo("para")
if name == 'main':
test_three_method()
executing foo(<main.A object at 0x100ba4e10>, para)
executing class_foo(<class 'main.A'>, para)
executing class_foo(<class 'main.A'>, para)
executing static_foo(para)
executing static_foo(para)
property裝飾器
定義私有類屬性
將property與裝飾器結合實現屬性私有化(更簡單安全的實現get和set方法)
Python
property(fget=None, fset=None, fdel=None, doc=None)
1
2
property(fget=None, fset=None, fdel=None, doc=None)
fget是獲取屬性的值的函數,fset是設置屬性值的函數,fdel是刪除屬性的函數,doc是一個字符串(like a comment).從實現來看,這些參數都是可選的
property有三個方法getter(), setter()和delete() 來指定fget, fset和fdel。 這表示如下這行
Python
class Student(object):
@property #至關於property.getter(score) 或者property(score)
def score(self):
return self._score
@score.setter #至關於score = property.setter(score)
def score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
1
2
3
4
5
6
7
8
9
10
11
class Student(object):
@property #至關於property.getter(score) 或者property(score)
def score(self):
return self._score
@score.setter #至關於score = property.setter(score)
def score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
iter魔法
經過yield和__iter__的結合, 咱們能夠把一個對象變成可迭代的
經過__str__的重寫, 能夠直接經過想要的形式打印對象
Python
class TestIter(object):
def init(self):
self.lst = [1, 2, 3, 4, 5]
def read(self):
for ele in xrange(len(self.lst)):
yield ele
def iter(self):
return self.read()
def str(self):
return ','.join(map(str, self.lst))
__repr__ = __str__
def test_iter():
obj = TestIter()
for num in obj:
print num
print obj
if name == 'main':
test_iter()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class TestIter(object):
def init(self):
self.lst = [1, 2, 3, 4, 5]
def read(self):
for ele in xrange(len(self.lst)):
yield ele
def iter(self):
return self.read()
def str(self):
return ','.join(map(str, self.lst))
__repr__ = __str__
def test_iter():
obj = TestIter()
for num in obj:
print num
print obj
if name == 'main':
test_iter()
神奇partial
partial使用上很像C++中仿函數(函數對象).
在stackoverflow給出了相似與partial的運行方式
Python
def partial(func, part_args):
def wrapper(extra_args):
args = list(part_args)
args.extend(extra_args)
return func(args)
return wrapper
1
2
3
4
5
6
def partial(func, part_args):
def wrapper(extra_args):
args = list(part_args)
args.extend(extra_args)
return func(args)
return wrapper
利用用閉包的特性綁定預先綁定一些函數參數, 返回一個可調用的變量, 直到真正的調用執行
Python
from functools import partial
def sum(a, b):
return a + b
def test_partial():
fun = partial(sum, 2) # 事先綁定一個參數, fun成爲一個只須要一個參數的可調用變量
print fun(3) # 實現執行的便是sum(2, 3)
if name == 'main':
test_partial()
5
1
2
3
4
5
6
7
8
9
10
11
12
13
from functools import partial
def sum(a, b):
return a + b
def test_partial():
fun = partial(sum, 2) # 事先綁定一個參數, fun成爲一個只須要一個參數的可調用變量
print fun(3) # 實現執行的便是sum(2, 3)
if name == 'main':
test_partial()
5
神祕eval
eval我理解爲一種內嵌的python解釋器(這種解釋可能會有誤差), 會解釋字符串爲對應的代碼並執行, 而且將執行結果返回
看一下下面這個例子
Python
def test_first():
return 3
def test_second(num):
return num
action = { # 能夠看作是一個sandbox
"para": 5,
"test_first" : test_first,
"test_second": test_second
}
def test_eavl():
condition = "para == 5 and test_second(test_first) > 5"
res = eval(condition, action) # 解釋condition並根據action對應的動做執行
print res
if name == '_
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def test_first():
return 3
def test_second(num):
return num
action = { # 能夠看作是一個sandbox
"para": 5,
"test_first" : test_first,
"test_second": test_second
}
def test_eavl():
condition = "para == 5 and test_second(test_first) > 5"
res = eval(condition, action) # 解釋condition並根據action對應的動做執行
print res
if name == '_
exec
exec在Python中會忽略返回值, 老是返回None, eval會返回執行代碼或語句的返回值
exec和eval在執行代碼時, 除了返回值其餘行爲都相同
在傳入字符串時, 會使用compile(source, '
Python
def test_first():
print "hello"
def test_second():
test_first()
print "second"
def test_third():
print "third"
action = {
"test_second": test_second,
"test_third": test_third
}
def test_exec():
exec "test_second" in action
if name == 'main':
test_exec() # 沒法看到執行結果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def test_first():
print "hello"
def test_second():
test_first()
print "second"
def test_third():
print "third"
action = {
"test_second": test_second,
"test_third": test_third
}
def test_exec():
exec "test_second" in action
if name == 'main':
test_exec() # 沒法看到執行結果
getattr
getattr(object, name[, default])Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, ‘foobar’) is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.
經過string類型的name, 返回對象的name屬性(方法)對應的值, 若是屬性不存在, 則返回默認值, 至關於object.name
Python
class TestGetAttr(object):
test = "test attribute"
def say(self):
print "test method"
def test_getattr():
my_test = TestGetAttr()
try:
print getattr(my_test, "test")
except AttributeError:
print "Attribute Error!"
try:
getattr(my_test, "say")()
except AttributeError: # 沒有該屬性, 且沒有指定返回值的狀況下
print "Method Error!"
if name == 'main':
test_getattr()
test attribute
test method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class TestGetAttr(object):
test = "test attribute"
def say(self):
print "test method"
def test_getattr():
my_test = TestGetAttr()
try:
print getattr(my_test, "test")
except AttributeError:
print "Attribute Error!"
try:
getattr(my_test, "say")()
except AttributeError: # 沒有該屬性, 且沒有指定返回值的狀況下
print "Method Error!"
if name == 'main':
test_getattr()
test attribute
test method
命令行處理
Python
def process_command_line(argv):
"""
Return a 2-tuple: (settings object, args list).
argv
is a list of arguments, or None
for sys.argv[1:]
.
"""
if argv is None:
argv = sys.argv[1:]
# initialize the parser object:
parser = optparse.OptionParser(
formatter=optparse.TitledHelpFormatter(width=78),
add_help_option=None)
# define options here:
parser.add_option( # customized description; put --help last
'-h', '--help', action='help',
help='Show this help message and exit.')
settings, args = parser.parse_args(argv)
# check number of arguments, verify values, etc.:
if args:
parser.error('program takes no command-line arguments; '
'"%s" ignored.' % (args,))
# further process settings & args if necessary
return settings, args
def main(argv=None):
settings, args = process_command_line(argv)
# application code here, like:
# run(settings, args)
return 0 # success
if name == 'main':
status = main()
sys.exit(status)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def process_command_line(argv):
"""
Return a 2-tuple: (settings object, args list).
argv
is a list of arguments, or None
for sys.argv[1:]
.
"""
if argv is None:
argv = sys.argv[1:]
# initialize the parser object:
parser = optparse.OptionParser(
formatter=optparse.TitledHelpFormatter(width=78),
add_help_option=None)
# define options here:
parser.add_option( # customized description; put --help last
'-h', '--help', action='help',
help='Show this help message and exit.')
settings, args = parser.parse_args(argv)
# check number of arguments, verify values, etc.:
if args:
parser.error('program takes no command-line arguments; '
'"%s" ignored.' % (args,))
# further process settings & args if necessary
return settings, args
def main(argv=None):
settings, args = process_command_line(argv)
# application code here, like:
# run(settings, args)
return 0 # success
if name == 'main':
status = main()
sys.exit(status)
讀寫csv文件
Python
import csv
with open('data.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
print row
import csv
with open( 'data.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerow(['name', 'address', 'age']) # 單行寫入
data = [
( 'xiaoming ','china','10'),
( 'Lily', 'USA', '12')]
writer.writerows(data) # 多行寫入
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import csv
with open('data.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
print row
import csv
with open( 'data.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerow(['name', 'address', 'age']) # 單行寫入
data = [
( 'xiaoming ','china','10'),
( 'Lily', 'USA', '12')]
writer.writerows(data) # 多行寫入
各類時間形式轉換
只發一張網上的圖, 而後差文檔就行了, 這個是記不住的
字符串格式化
一個很是好用, 不少人又不知道的功能
Python
name = "andrew"
"my name is {name}".format(name=name)
'my name is andrew'
1
2
3
name = "andrew"
"my name is {name}".format(name=name)
'my name is andrew'
Python編碼規範(PEP8)及奇技淫巧(不斷更新)
2017年04月04日 19:18:00
閱讀數:4309
Python 2.7
前言
從不少地方搬運+總結,之後根據這個標準再將python的一些奇技淫巧結合起來,寫出更pythonic的代碼~
PEP8 編碼規範
英文原版請點擊這裏
如下是@bobo的整理,原文請見PEP8 Python 編碼規範整理
代碼編排
縮進。4個空格的縮進(編輯器均可以完成此功能),不使用Tap,更不能混合使用Tap和空格。
每行最大長度79,換行可使用反斜槓,最好使用圓括號。換行點要在操做符的後邊敲回車。
類和top-level函數定義之間空兩行;類中的方法定義之間空一行;函數內邏輯無關段落之間空一行;其餘地方儘可能不要再空行。
文檔編排
模塊內容的順序:模塊說明和docstring—import—globals&constants—其餘定義。其中import部分,又按標準、三方和本身編寫順序依次排放,之間空一行
不要在一句import中多個庫,好比import os, sys不推薦
若是採用from XX import XX引用庫,能夠省略‘module.’,都是可能出現命名衝突,這時就要採用import XX
空格的使用
各類右括號前不要加空格。
逗號、冒號、分號前不要加空格。
函數的左括號前不要加空格。如Func(1)
序列的左括號前不要加空格。如list[2]
操做符左右各加一個空格,不要爲了對齊增長空格
函數默認參數使用的賦值符左右省略空格
不要將多句語句寫在同一行,儘管使用‘;’容許
if/for/while語句中,即便執行語句只有一句,也必須另起一行
註釋
整體原則,錯誤的註釋不如沒有註釋。因此當一段代碼發生變化時,第一件事就是要修改註釋!註釋必須使用英文,最好是完整的句子,首字母大寫,句後要有結束符,結束符後跟兩個空格,開始下一句。若是是短語,能夠省略結束符。
塊註釋,在一段代碼前增長的註釋。在‘#’後加一空格。段落之間以只有‘#’的行間隔。好比:
1
2
3
4
5
行註釋,在一句代碼後加註釋。好比:x = x + 1 # Increment x可是這種方式儘可能少使用。
避免無謂的註釋。
文檔描述
爲全部的共有模塊、函數、類、方法寫docstrings;非共有的沒有必要,可是能夠寫註釋(在def的下一行)。
單行註釋請參考以下方式
def kos_root():
"""Return the pathname of the KOS root directory."""
global _kos_root
if _kos_root: return _kos_root
...
1
2
3
4
5
命名規則
模塊命名儘可能短小,使用所有小寫的方式,可使用下劃線。
包命名儘可能短小,使用所有小寫的方式,不可使用下劃線。
類的命名使用CapWords的方式,模塊內部使用的類採用_CapWords的方式。
異常命名使用CapWords+Error後綴的方式。
全局變量儘可能只在模塊內有效,相似C語言中的static。實現方法有兩種,一是all機制;二是前綴一個下劃線。
函數命名使用所有小寫的方式,可使用下劃線。
常量命名使用所有大寫的方式,可使用下劃線。
類的屬性(方法和變量)命名使用所有小寫的方式,可使用下劃線。
類的屬性有3種做用域public、non-public和subclass API,能夠理解成C++中的public、private、protected,non-public屬性前,前綴一條下劃線。
類的屬性若與關鍵字名字衝突,後綴一下劃線,儘可能不要使用縮略等其餘方式。
爲避免與子類屬性命名衝突,在類的一些屬性前,前綴兩條下劃線。好比:類Foo中聲明__a,訪問時,只能經過Foo._Foo__a,避免歧義。若是子類也叫Foo,那就無能爲力了。
類的方法第一個參數必須是self,而靜態方法第一個參數必須是cls。
編程建議
編碼中考慮到其餘python實現的效率等問題,好比運算符‘+’在CPython(Python)中效率很高,都是Jython中卻很是低,因此應該採用.join()的方式。
儘量使用‘is’‘is not’取代‘==’,好比if x is not None 要優於if x
使用基於類的異常,每一個模塊或包都有本身的異常類,此異常類繼承自Exception。
常中不要使用裸露的except,except後跟具體的exceptions。例如
try:
...
except Exception as ex:
print ex
1
2
3
4
異常中try的代碼儘量少。
使用startswith() and endswith()代替切片進行序列前綴或後綴的檢查。
foo = 'abc000xyz'
if foo.startswith('abc') and foo.endswith('xyz'):
print 'yes'
else:
print 'no'
if foo[:3]=='abc' and foo[-3:]=='xyz':
print 'yes'
else:
print 'no'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
使用isinstance()比較對象的類型。好比:
foo = 'abc000xyz'
print isinstance(foo,int) # false
print type(foo) == type('1') #true
1
2
3
4
5
6
7
判斷序列空或不空,有以下規則:
foo = 'abc000xyz'
if foo:
print "not empty"
else:
print "empty"
if len(foo):
print "not empty"
else:
print "empty"
1
2
3
4
5
6
7
8
9
10
11
12
二進制數據判斷使用 if boolvalue的方式。
給本身的代碼打分
使用pylint進行代碼檢查,@permilk–Python代碼分析工具:PyChecker、Pylint
pip install pylint
1
2
寫一段測試代碼,命名爲test.py
def parttion(vec, left, right):
key = vec[left]
low = left
high = right
while low < high:
while (low < high) and (vec[high] >= key):
high -= 1
vec[low] = vec[high]
while (low < high) and (vec[low] <= key):
low += 1
vec[high] = vec[low]
vec[low] = key
return low
def quicksort(vec, left, right):
if left < right:
p = parttion(vec, left, right)
quicksort(vec, left, p-1) # 再一樣處理分片問題
quicksort(vec, p+1, right)
return vec
before_list = [4, 6, 1, 3, 5, 9]
print "before sort:", before_list
after_list = quicksort(before_list, left=0, right=len(before_list)-1)
print"after sort:", after_list
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
進行代碼規範測試
pylint test.py
Problem importing module variables.py: No module named functools_lru_cache
Problem importing module variables.pyc: No module named functools_lru_cache
No config file found, using default configuration
************* Module test
C: 24, 0: Trailing whitespace (trailing-whitespace)
C: 1, 0: Missing module docstring (missing-docstring)
C: 5, 0: Missing function docstring (missing-docstring)
C: 20, 0: Missing function docstring (missing-docstring)
C: 22, 8: Invalid variable name "p" (invalid-name)
C: 28, 0: Invalid constant name "before_list" (invalid-name)
C: 30, 0: Invalid constant name "after_list" (invalid-name)
23 statements analysed.
+---------+-------+-----------+-----------+------------+---------+
|type |number |old number |difference |%documented |%badname |
+=========+=======+===========+===========+============+=========+
|module |1 |1 |= |0.00 |0.00 |
+---------+-------+-----------+-----------+------------+---------+
|class |0 |0 |= |0 |0 |
+---------+-------+-----------+-----------+------------+---------+
|method |0 |0 |= |0 |0 |
+---------+-------+-----------+-----------+------------+---------+
|function |2 |2 |= |0.00 |0.00 |
+---------+-------+-----------+-----------+------------+---------+
+----------+-------+------+---------+-----------+
|type |number |% |previous |difference |
+==========+=======+======+=========+===========+
|code |23 |71.88 |23 |= |
+----------+-------+------+---------+-----------+
|docstring |0 |0.00 |0 |= |
+----------+-------+------+---------+-----------+
|comment |5 |15.62 |5 |= |
+----------+-------+------+---------+-----------+
|empty |4 |12.50 |4 |= |
+----------+-------+------+---------+-----------+
+-------------------------+------+---------+-----------+
| |now |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines |0 |0 |= |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000 |= |
+-------------------------+------+---------+-----------+
+-----------+-------+---------+-----------+
|type |number |previous |difference |
+===========+=======+=========+===========+
|convention |7 |7 |= |
+-----------+-------+---------+-----------+
|refactor |0 |0 |= |
+-----------+-------+---------+-----------+
|warning |0 |0 |= |
+-----------+-------+---------+-----------+
|error |0 |0 |= |
+-----------+-------+---------+-----------+
+--------------------+------------+
|message id |occurrences |
+====================+============+
|missing-docstring |3 |
+--------------------+------------+
|invalid-name |3 |
+--------------------+------------+
|trailing-whitespace |1 |
+--------------------+------------+
Your code has been rated at 6.96/10 (previous run: 6.96/10, +0.00)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
Python奇技淫巧
使用 Counter 進行計數統計
from collections import Counter
Counter(s=3, c=2, e=1, u=1)
Counter({'s': 3, 'c': 2, 'u': 1, 'e': 1})
some_data=('c', '2', 2, 3, 5, 'c', 'd', 4, 5, 'd', 'd')
Counter(some_data).most_common(2)
[('d', 3), ('c', 2)]
some_data=['c', '2', 2, 3, 5, 'c', 'd', 4, 5, 'd', 'd']
Counter(some_data).most_common(2)
[('d', 3), ('c', 2)]
some_data={'c', '2', 2, 3, 5, 'c', 'd', 4, 5, 'd', 'd'}
Counter(some_data).most_common(2)
[('c', 1), (3, 1)]
1
2
3
4
5
6
7
8
9
10
11
12
13
enumerate獲取鍵值對
在同時須要index和value值的時候可使用 enumerate。下列分別將字符串,數組,列表與字典遍歷序列中的元素以及它們的下標
for i,j in enumerate('abcde'):
... print i,j
...
0 a
1 b
2 c
3 d
4 e
for i,j in enumerate([1,2,3,4]):
... print i,j
...
0 1
1 2
2 3
3 4
for i,j in enumerate([1,2,3,4],start=1):
... print i,j
...
1 1
2 2
3 3
4 4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from collections import defaultdict
s = "the quick brown fox jumps over the lazy dog"
words = s.split()
location = defaultdict(list)
for m, n in enumerate(words):
location[n].append(m)
print location
1
2
3
4
5
6
7
8
9
10
11
12
13
14
os.path的使用
os.path.join用於拼接路徑,好處是能夠根據系統自動選擇正確的路徑分隔符」/」或」」
os.path.split 把路徑分割成dirname和basename,返回一個元組
os.listdir 獲取路徑下全部文件,返回list
import os
path=os.path.abspath("ams8B.zip")
print path # /Users/didi/Desktop/testhelp/ams8B.zip # 實際上該文件夾下沒有ams8B.zip
print os.path.join("/".join(path.split("/")[:-1]),'ams8B.gz') # /Users/didi/Desktop/testhelp/ams8B.gz
print os.path.join("home","user","test") # home/user/test
print os.path.split(path) # ('/Users/didi/Desktop/testhelp', 'ams8B.zip')
print os.path.join(os.path.split(path)[0],'ams8B.gz') # /Users/didi/Desktop/testhelp/ams8B.gz
print os.getcwd() # /Users/didi/Desktop/testhelp
print os.listdir(os.getcwd()) # ['t1.txt', 'test1.py', 'test2.py', '\xe6\x8e\xa5\xe9\xa9\xbeeta\xe5\x88\x86\xe5\xb8\x83.sh']
1
2
3
4
5
6
7
8
9
10
11
善用列表推導式
foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
print filter(lambda x: x % 3 == 0, foo)
[18, 9, 24, 12, 27]print map(lambda x: x * 2 + 10, foo)
[14, 46, 28, 54, 44, 58, 26, 34, 64]print reduce(lambda x, y: x + y, foo)
139
1
2
3
4
5
6
7
8
9
使用列表推導式
[x * 2 + 10 for x in foo]
[14, 46, 28, 54, 44, 58, 26, 34, 64]
[x for x in foo if x % 3 == 0]
[18, 9, 24, 12, 27]
1
2
3
4
對於輕量級循環,可儘可能使用列表推導式,熟練使用列表推導式能夠不少狀況下代替map,filter等
foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
foo
[2, 18, 9, 22, 17, 24, 8, 12, 27]
['>3' if i>3 else '<3' for i in foo]
['<3', '>3', '>3', '>3', '>3', '>3', '>3', '>3', '>3']
t=map(lambda x:'<3' if x<3 else '>3',foo)
t
['<3', '>3', '>3', '>3', '>3', '>3', '>3', '>3', '>3']1
2
3
4
5
6
7
8
9
可參考:最簡單的理解lambda,map,reduce,filter,列表推導式
sort 與 sorted
sorted(iterable[, cmp[, key[, reverse]]]) # 返回一個排序後的列表
s.sort([cmp[, key[, reverse]]]) # 直接修改原列表,返回爲None
persons = [{'name': 'Jon', 'age': 32}, {'name': 'Alan', 'age': 50}, {'name': 'Bob', 'age': 23}]
sorted(persons, key=lambda x: (x['name'], -x['age']))
[{'name': 'Alan', 'age': 50}, {'name': 'Bob', 'age': 23}, {'name': 'Jon', 'age': 32}]
a = (1, 2, 4, 2, 3)
sorted(a)
[1, 2, 2, 3, 4]
students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10),]
sorted(students, key=lambda student : student[2]) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
1
2
3
4
5
6
7
8
9
10
11
12
13
因此若是實際過程當中須要保留原有列表,可使用sorted()。sort()不須要複製原有列表,消耗內存較小,效率較高。同時傳入參數key比傳入參數cmp效率要高,cmp傳入的函數在整個排序過程當中會調用屢次,而key針對每一個元素僅做一次處理。
關於cmp的使用,這位哥們總算踩到點python中sort()方法自定義cmp PythonTip-最大正整數
def Reverse(a,b):
return b-a
list_ = [5,3,4,1,2]
new = sorted(list_,cmp=ps)
print new # [5, 4, 3, 2, 1]
1
2
3
4
5
6
7
8
9
10
善用traceback 追蹤深層錯誤
import traceback
try:
do something
except Exception as ex:
print ex
traceback.print_exc()
1
2
3
4
5
6
7
8
切片操做[]
至關於淺copy的做用
a=[1,2,3]
b=a[:]
b.append(4)
b
[1, 2, 3, 4]
a
[1, 2, 3]
import copy
c=copy.copy(a)
c
[1, 2, 3]
c.append(4)
a
[1, 2, 3]
c
[1, 2, 3, 4]
d=a
d.append(4)
d
[1, 2, 3, 4]
a
[1, 2, 3, 4]
import copy
a = [[1,2],3,4]
b = copy.copy(a)
id(a)
54936008L
id(b)
54964680L
a is b
False
b
[[1, 2], 3, 4]
b[0][1]
2
b[0][1]=2333
b
[[1, 2333], 3, 4]
a
[[1, 2333], 3, 4]
a = [[1,2],3,4]
c = copy.deepcopy(a)
id(a)
55104008L
id(c)
54974536L
a is c
False
c
[[1, 2], 3, 4]
c[0][1]
2
c[0][1]=233
c
[[1, 233], 3, 4]
a
[[1, 2], 3, 4] # 不會隨之改變
d = a[:]
d
[[1, 2], 3, 4]
d[0][1]=0
d
[[1, 0], 3, 4]
a
[[1, 0], 3, 4] # 會隨之改變
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
進行逆序排列
b
[1, 2, 3, 4]
b[::-1]
[4, 3, 2, 1]
1
2
3
4
json.dump()/loads() 存儲字典結構
import json
dict_ = {1:2, 3:4, "55":"66"}
json_str = json.dumps(dict_)
print type(json_str), json_str
print type(json.loads(json_str))
1
2
3
4
5
6
7
8
9
10
11
pprint打印結構
from pprint import pprint
data = [(1,{'a':'A','b':'B','c':'C','d':'D'}),
(2,{'e':'E','f':'F','g':'G','h':'H', 'i':'I','j':'J','k':'K','l':'L' }),]
print data
pprint(data)
[(1, {'a': 'A', 'c': 'C', 'b': 'B', 'd': 'D'}), (2, {'e': 'E', 'g': 'G', 'f': 'F', 'i': 'I', 'h': 'H', 'k': 'K', 'j': 'J', 'l': 'L'})]
[(1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}),
(2,
{'e': 'E',
'f': 'F',
'g': 'G',
'h': 'H',
'i': 'I',
'j': 'J',
'k': 'K',
'l': 'L'})]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
zip打包元組
定義:zip([seql, …])接受一系列可迭代對象做爲參數,將對象中對應的元素打包成一個個tuple(元組),而後返回由這些tuples組成的list(列表)。若傳入參數的長度不等,則返回list的長度和參數中長度最短的對象相同。
name = ['mrlevo','hasky']
kind = ['human','dog']
z1 = [1,2,3]
z2 = [4,5,6]
result = zip(z1,z2) # 壓縮過程
uzip= zip(*result) # 解壓過程,拆分爲元組
print "the zip:",result
print "the uzip:",uzip
print "the uzip part of z1:%s\nthe uzip part of z2:%s"%(str(uzip[0]),str(uzip[1]))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
*args和**kw
args僅僅只是用在函數定義的時候用來表示位置參數應該存儲在變量args裏面。Python容許咱們制定一些參數而且經過args捕獲其餘全部剩餘的未被捕捉的位置。當調用一個函數的時候,一個用標誌的變量意思是變量裏面的內容須要被提取出來而後當作位置參數被使用。
def add(x, y):
return x + y
list_ = [1,2]
add(list_[0], list_[1]) # 3
add(list_) # 3
1
2
3
4
5
6
args要麼是表示調用方法大的時候額外的參數能夠從一個可迭代列表中取得,要麼就是定義方法的時候標誌這個方法可以接受任意的位置參數。接下來提到的,kw表明着鍵值對的字典,也就是說,你不用一個個字典用key來取value了
dict_ = {'x': 1, 'y': 2, 'z':3}
def bar(x, y, z):
return x + y + z
bar(**dict_) # 6
bar(dict_['x'],dict_['y'],dict_['z']) # 6
1
2
3
4
5
6
內建函數 itertools優雅的迭代器
方法不少,就先介紹筆試題碰到的permutations
permutations(p[,r]);返回p中任意取r個元素作排列的元組的迭代器
如:permutations(‘abc’, 2) # 從’abcd’中挑選兩個元素,好比ab, bc, … 將全部結果排序,返回爲新的循環器。
注意,上面的組合分順序,即ab, ba都返回。
combinations(‘abc’, 2) # 從’abcd’中挑選兩個元素,好比ab, bc, … 將全部結果排序,返回爲新的循環器。
注意,上面的組合不分順序,即ab, ba的話,只返回一個ab。
再來個實際點的算法的一個例子,雖然毫無算法結構可言
import itertools
def Permutation(ss):
# write code here
if not ss:
return []
return sorted(list(set(map(lambda x:''.join(x), itertools.permutations(ss)))))
Permutation('abc')