질문
I have a list with 15 numbers. How can I produce all 32,768 combinations of those numbers (i.e., any number of elements, in the original order)?
I thought of looping through the decimal integers 1–32768 and using the binary representation of each numbers as a filter to pick out the appropriate list elements. Is there a better way to do it?
For combinations of a specific length, see Get all (n-choose-k) combinations of length n. Please use that question to close duplicates instead where appropriate.
When closing questions about combinatorics as duplicates, it is very important to make sure of what OP actually wants, not the words that were used to describe the problem. It is extremely common for people who want, for example, a Cartesian product (see How to get the cartesian product of multiple lists) to ask about "combinations".
답변
이 답변은 한 가지 측면을 놓친다: OP는 모든 조합을 요청했는데, 그냥 길이 "r"의 조합만을 요청한 게 아니다.
그래서 모든 길이 "L"을 반복해야 한다:
import itertools
stuff = [1, 2, 3]
for L in range(len(stuff) + 1):
for subset in itertools.combinations(stuff, L):
print(subset)
또는 -- 멋있게 하려면 (또는 당신 뒤에 코드를 읽는 사람의 머리를 아프게 하려면) -- "combinations()" 생성기의 체인을 생성하고 그것을 반복할 수도 있다:
from itertools import chain, combinations
def all_subsets(ss):
return chain(*map(lambda x: combinations(ss, x), range(0, len(ss)+1)))
for subset in all_subsets(stuff):
print(subset)
댓글