![]() | 1 | initial version |
I'm not completely sure I understand your question, but what you're asking for sounds simply (at least almost simply) like cartesian product, which is implemented in Python in itertools.product. In the basic case, you could then just do:
sage: L = [ [1,2,3,4],[3,5,6,7],[7,8,9,10] ] # note that this is a list, while you did a tuple
sage: from itertools import product
sage: list(product(L, L))
[([1, 2, 3, 4], [1, 2, 3, 4]), ([1, 2, 3, 4], [3, 5, 6, 7]), ...
(note the "list" around product, as product returns a generator) However, this would also give those sublists with two equal elements in it. If you don't want this, you can write a simple list-comprehension to do it:
sage: [ [a,b] for a in L for b in L if a != b ]
[[[1, 2, 3, 4], [3, 5, 6, 7]], [[1, 2, 3, 4], [7, 8, 9, 10]], [[3, 5, 6, 7], [1, 2, 3, 4]], [[3, 5, 6, 7], [7, 8, 9, 10]], [[7, 8, 9, 10], [1, 2, 3, 4]], [[7, 8, 9, 10], [3, 5, 6, 7]]]
However, this has the drawback (I think) of creating the entire list in memory instead of being a light generator as the product returns. You would have to write a longer piece of code to get a generator with the above behaviour.
Note that this is all Python-stuff and not specific to Sage at all.
Cheers, Johan
![]() | 2 | No.2 Revision |
I'm not completely sure I understand your question, but what you're asking for sounds simply (at least almost simply) like cartesian product, which is implemented in Python in itertools.product. In the basic case, you could then just do:
sage: L = [ [1,2,3,4],[3,5,6,7],[7,8,9,10] ] # note that this is a list, while you did a tuple
sage: from itertools import product
sage: list(product(L, L))
[([1, 2, 3, 4], [1, 2, 3, 4]), ([1, 2, 3, 4], [3, 5, 6, 7]), ...
(note the "list" around product, as product returns a generator)
generator)
The above can easily be generalised to having 3,4,...,n elements in each sublist (i.e. L^n) by modifying the last line to
list(product(repeat(L, n)))
However, this would also give those sublists with two equal elements in it. where the same element might be present more than once in each list. If you don't want this, you can write a simple list-comprehension to do it:handle the 2-case:
sage: [ [a,b] for a in L for b in L if a != b ]
[[[1, 2, 3, 4], [3, 5, 6, 7]], [[1, 2, 3, 4], [7, 8, 9, 10]], [[3, 5, 6, 7], [1, 2, 3, 4]], [[3, 5, 6, 7], [7, 8, 9, 10]], [[7, 8, 9, 10], [1, 2, 3, 4]], [[7, 8, 9, 10], [3, 5, 6, 7]]]
However, Manually, the above can also be extended to 3, 4, ... but not easily to any number n given as a parameter. Also, this has the drawback (I think) of creating the entire list in memory instead of being a light generator as the product returns. You would have to write a longer piece of code to get a generator with the above behaviour.
Note that this is all Python-stuff and not specific to Sage at all.
Cheers, Johan