0

我几乎完成了有人给我的任务,最初涉及轻松使用 itertools 中的 product() 函数。但是,该人要求它也应该做一些不同的事情,例如:

李=

[[1, 2, 3],
[4, 5, 6]]

一个常规的 product() 会给出类似:[1, 4], [1, 5], [1, 6], [2, 4], [2, 5], [2, 6], [3, 4 ] ...

它应该做的是:

执行常规 product(),然后从列表中的第一个元素添加下一项,依此类推。一套完整的例子是:

[[1, 4, 2]
[1, 4, 3],
[1, 5, 2],
[1, 5, 3],
[2, 4, 3],
[2, 5, 3],
[2 , 6, 3]]

在这种情况下我应该如何使用 itertools?

编辑:

如果我解释程序的目标可能会有所帮助:例如,用户将输入一个 5 行 x 6 列的数字列表。
一个正常的 product() 将产生一个 5 个数字的组合。这个人想要一个 6 位数的组合。这个“第 6 个”数字从何而来?这将来自他对他想要哪一行的选择。

4

2 回答 2

1

我想知道您执行的神奇计算是什么,但看起来这就是您的公式:

k = int(raw_input('From What row items should be appeared again at the end?'))
res = [l for l in product(*(li+[li[k]])) if l[k]<l[len(li)] ]
于 2010-08-17T20:09:07.130 回答
1

泛化为两个以上的子列表(地图函数将是另一种选择)

from pprint import pprint
for li in ([[1, 2, 3],
            [4, 5, 6]],

           [[1,  2,  3,  4],
            [5,  6,  7,  8],
            [9, 10, 11, 12]]
           ):
    triples= []
    prevlist=li[0]
    for nextlist in li[1:]:
        for spacing in range(1,len(prevlist)):
            triples.extend([[first,other,second]
                            for first,second in zip(prevlist,prevlist[spacing:])
                            for other in nextlist])

    pprint(sorted(triples))
于 2010-08-17T20:09:50.900 回答