세트 S의 n 개의 사본은 S n으로 표시됩니다. 예를 들어, {0, 1} 3은 3 비트 시퀀스들의 집합이다 :Python에서 제품 설정
{0,1} 3 = {(0,0,0), (0,0,1) , (0,1,0), (0,1,1), (1,0,0), (1,0,1), (1,1,0), (1,1,1)}
이 아이디어를 파이썬에서 재사용하는 가장 간단한 방법은 무엇입니까?
세트 S의 n 개의 사본은 S n으로 표시됩니다. 예를 들어, {0, 1} 3은 3 비트 시퀀스들의 집합이다 :Python에서 제품 설정
{0,1} 3 = {(0,0,0), (0,0,1) , (0,1,0), (0,1,1), (1,0,0), (1,0,1), (1,1,0), (1,1,1)}
이 아이디어를 파이썬에서 재사용하는 가장 간단한 방법은 무엇입니까?
이상이 선택적 인수 repeat
으로 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)
: 당신이 설명서에있는 코드를 사용하여
product
를 구현할 수 있습니다 파이썬 이전 버전의
>>> from itertools import product
>>> s1 = set((0, 1))
>>> set(product(s1, repeat = 3))
나는 이것이 작동한다고 생각하니?
>>> 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
임의의 n뿐만 아니라 임의의 집합도 좋을 것입니다. – Eugene