开发者

Special type of combination using itertools

开发者 https://www.devze.com 2023-01-11 19:28 出处:网络
I am almost finished with a task someone gave me that at first involved easy use of the produ开发者_如何学编程ct() function from itertools.

I am almost finished with a task someone gave me that at first involved easy use of the produ开发者_如何学编程ct() function from itertools. However, the person asked that it should also do something a bit different like:

li =

[[1, 2, 3],

[4, 5, 6]]

A regular product() would give something like: [1, 4], [1, 5], [1, 6], [2, 4], [2, 5], [2, 6], [3, 4] ...

What it should do is:

Do a regular product(), then, add the next item from the first element in the list and so on. A complete set of example would be:

[[1, 4, 2]

[1, 4, 3],

[1, 5, 2],

[1, 5, 3],

[2, 4, 3],

[2, 5, 3],

[2, 6, 3]]

How should I use itertools in this circumstance?

EDIT:

It might help if I explain the goal of the program: The user will enter, for example, a 5 row by 6 column list of numbers.

A normal product() will result in a 5-number combination. The person wants a 6-number combination. Where will this "6th" number come from? It would come from his choice of which row he wants.


I wondering what is the magical computations you performing, but it look's like that's your formula:

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)] ]


Generalized for more than two sublist (map function would be the other alternative)

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))
0

精彩评论

暂无评论...
验证码 换一张
取 消