[英]Cartesian Product without Itertools A Non Pythonic approach
我在這里有此代碼:
import itertools
col_groups = [c1+c2 for c1, c2 in itertools.product(d1_columns, d2_columns)]
沒有itertools,我該怎么做? 一種非Python的方式。
如果只需要兩個列表的笛卡爾積,也許可以使用嵌套列表理解。
[ i + j for i in d1_columns for j in d2_columns ]
def colGroups(d1, d2):
answer = []
for c1 in d1:
for c2 in d2:
answer.append(c1+c2)
return answer
測試:
>>> d1 = list(range(10))
>>> d2 = list(range(10,20))
>>> d1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> d2
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> def colGroups(d1, d2):
... answer = []
... for c1 in d1:
... for c2 in d2:
... answer.append(c1+c2)
... return answer
...
>>> colGroups(d1, d2)
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28]
...或等效的嵌套listcomp:
colGroups = [c1+c2 for c1 in d1 for c2 in d2]
您始終可以使用itertools.product中提供的代碼
def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.