在Python中查找组合而不导入itertools

Mys*_*des -3 python combinations

我想要在Python中完成以下任务而不导入任何模块.

我的守则包括

Two List
---------
list1=['aun','2ab','acd','3aa']
list2=['ca3','ba2','dca','aa3']

Function
---------
Run Code Online (Sandbox Code Playgroud)

它会在哪里:

  • 从list1生成2个项目组合
  • 从list2生成2个项目组合
  • 从list1和list2生成2个项目组合

我不需要打印这两个项目的所有组合

但是我希望将所有这两个项目组合传递给进一步的任务并显示结果

 analysize R.. **ca3** .... and ... **2ab** // Combinations of two items from list1 and list2

 Print analysize
Run Code Online (Sandbox Code Playgroud)

Tim*_*ker 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)
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)