集合S的n個拷貝的乘積記作S n。例如,{0,1} 是集合中的所有3位序列:用Python設置產品
{0,1} = {(0,0,0),(0,0,1) ,(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)}
在Python中複製這個想法的最簡單方法是什麼?
集合S的n個拷貝的乘積記作S n。例如,{0,1} 是集合中的所有3位序列:用Python設置產品
{0,1} = {(0,0,0),(0,0,1) ,(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)}
在Python中複製這個想法的最簡單方法是什麼?
在Python 2.6或更新版本,您可以使用itertools.product與可選參數repeat
:
>>> from itertools import product
>>> s1 = set((0, 1))
>>> set(product(s1, repeat = 3))
對於舊版本的Python,您可以使用文檔中找到的代碼實現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)
我想這可行嗎?
>>> s1 = set((0,1))
>>> set(itertools.product(s1,s1,s1))
set([(0, 1, 1), (1, 1, 0), (1, 0, 0), (0, 0, 1), (1, 0, 1), (0, 0, 0), (0, 1, 0), (1, 1, 1)])
馬克,好主意。
>>> def set_product(the_set, n):
return set(itertools.product(the_set, repeat=n))
>>> s2 = set((0,1,2))
>>> set_product(s2, 3)
set([(0, 1, 1), (0, 1, 2), (1, 0, 1), (0, 2, 1), (2, 2, 0), (0, 2, 0), (0, 2, 2), (1, 0, 0), (2, 0, 1), (1, 2, 0), (2, 0, 0), (1, 2, 1), (0, 0, 2), (2, 2, 2), (1, 2, 2), (2, 0, 2), (0, 0, 1), (0, 0, 0), (2, 1, 2), (1, 1, 1), (0, 1, 0), (1, 1, 0), (2, 1, 0), (2, 2, 1), (2, 1, 1), (1, 1, 2), (1, 0, 2)])
您還可以擴展設置類型並使__pow__
方法執行此操作。
print 'You can do like this with generator:'
print set((a,b,c) for a in s1 for b in s1 for c in s1)
它只是{0,1}還是它可以是任何東西? – st0le 2010-07-17 14:55:48
任意集會很好,以及任意n。 – Eugene 2010-07-17 15:00:08