在Python中不使用itertools查找组合
我想在Python中完成以下任务,不想导入任何模块。
我的代码包括:
Two List
---------
list1=['aun','2ab','acd','3aa']
list2=['ca3','ba2','dca','aa3']
Function
---------
这个代码会:
- 从列表1中生成2个项目的组合
- 从列表2中生成2个项目的组合
- 从列表1和列表2中生成2个项目的组合
我不需要打印出所有这些2个项目的组合
但我想把所有这些2个项目的组合传递给后续的任务,并展示结果
analysize R.. **ca3** .... and ... **2ab** // Combinations of two items from list1 and list2
Print analysize
1 个回答
6
好吧,你已经知道怎么用 itertools
来实现这个功能了。如果你想不使用这个模块(不管是什么原因……),你可以看看这个 和 这个文档,了解一下源代码:
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)
还有
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)