可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
What I'd need is to create combinations for two elements a time.
if a list contains: seq = ['A', 'B', 'C']
the output would be com = [['A', 'B'], ['A', 'C'], ['B', 'C']]
all this without "itertools.combinations" method.
I was used to use this code for the permutations. But how could I modify the code to make it work with the combinations?
def permute(seq):
if len(seq) <= 1:
perms = [seq]
else:
perms = []
for i in range(len(seq)):
sub = permute(seq[:i]+seq[i+1:])
for p in sub:
perms.append(seq[i:i+1]+p)
return perms
回答1:
If you don't want to use itertools
, then use the documented pure-Python equivalent:
def combinations(iterable, r):
# combinations('ABCD', 2) --> AB AC AD BC BD CD
# combinations(range(4), 3) --> 012 013 023 123
pool = tuple(iterable)
n = len(pool)
if r > n:
return
indices = range(r)
yield tuple(pool[i] for i in indices)
while True:
for i in reversed(range(r)):
if indices[i] != i + n - r:
break
else:
return
indices[i] += 1
for j in range(i+1, r):
indices[j] = indices[j-1] + 1
yield tuple(pool[i] for i in indices)
回答2:
This is trivial to do directly:
def comb2(s):
for i, v1 in enumerate(s):
for j in range(i+1, len(s)):
yield [v1, s[j]]
Then:
print list(comb2(['A', 'B', 'C']))
displays:
[['A', 'B'], ['A', 'C'], ['B', 'C']]
The only thing that makes combinations at all tricky is catering to a known-only-at-runtime number of elements to take at a time. So long as you know that number in advance, a fixed number of loops nested that deep does the job in an obvious way.
回答3:
def combo2(lst,n):
if n==0:
return [[]]
l=[]
for i in range(0,len(lst)):
m=lst[i]
remLst=lst[i+1:]
for p in combo2(remLst,n-1):
l.append([m]+p)
return l
Input:
combo2(list('ABC'),2)
Output:
[['A', 'B'], ['A', 'C'], ['B', 'C']]
回答4:
Here's a loose translation of the recursive C++ code in an answer to a similar question:
def combinations(sequence, length, NULL=object()):
""" Find all combinations of the specified length from a sequence. """
if length <= 0:
combos = [NULL]
else:
combos = []
for i, item in enumerate(sequence, 1):
rem_items = sequence[i:]
rem_combos = combinations(rem_items, length-1)
combos.extend(item if combo is NULL else [item, combo]
for combo in rem_combos)
return combos
print(combinations(['A', 'B', 'C'], 2))
Output:
[['A', 'B'], ['A', 'C'], ['B', 'C']]