Generate Cartesian Products with Itertools Incrementally - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Generate Cartesian Products with Itertools Incrementally (/thread-27374.html) |
Generate Cartesian Products with Itertools Incrementally - CoderMan - Jun-04-2020 Hello, I know I can get Cartesian products using itertools.product(a,b)Assuming that a = ['a','b']and b = ['1','2']the result would be (a1,a2,b1,b2). How can I get the result (a,b,a1,a2,b1,b2)? That is, how can I get the shortest possible products first and then increment to the longest ones? Thanks RE: Generate Cartesian Products with Itertools Incrementally - bowlofred - Jun-04-2020 The first two elements of the list you want aren't products at all, unless you extend the range of possibilities like a = ['', 'a', 'b'] .If you do that, then you could generate them and sort the result. But I'm not sure I understand exactly what list you want. >>> a = ['', 'a', 'b'] >>> b = ['', '1', '2'] >>> sorted(["".join(x) for x in product(a,b)], key=len) ['', '1', '2', 'a', 'b', 'a1', 'a2', 'b1', 'b2'] RE: Generate Cartesian Products with Itertools Incrementally - CoderMan - Jun-04-2020 I actually figured it out. incremental_append = [] for characterSet in (a,b): incremental_append.append(char) for result in itertools.product(*incremental_append): print(result)Thank you anyways for the help. |