在量化數據處理中,常用itertools來完成數據的各類排列組合以尋找最優參數數組
1、數據準備函數
import itertools items = [1, 2, 3] ab = ['a', 'b'] cd = ['c', 'd']
#1. permutations: 考慮順序組合元素spa
for item in itertools.permutations(items): print(item)
返回code
(1, 2, 3) (1, 3, 2) (2, 1, 3) (2, 3, 1) (3, 1, 2) (3, 2, 1)
#2. combinations,不考慮順序,不放回數據blog
for item in itertools.combinations(items, 2): print(item)
返回it
(1, 2) (1, 3) (2, 3)
# 3. combinations_with_replacement,不考慮順序,有放回數據io
for item in itertools.combinations_with_replacement(items, 2): print(item)
返回class
(1, 1) (1, 2) (1, 3) (2, 2) (2, 3) (3, 3)
# 4. product()函數,迪卡爾積,在參數組合中尋找最優參數import
針對ab,cd兩個集合進行排列組合im
for item in itertools.product(ab, cd): print(item)
返回
('a', 'c') ('a', 'd') ('b', 'c') ('b', 'd')