Python Forum
Generate Cartesian Products with Itertools Incrementally
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Generate Cartesian Products with Itertools Incrementally
#1
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
Reply
#2
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']
Reply
#3
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  why does VS want to install seemingly unrelated products? db042190 3 608 Jun-12-2023, 02:47 PM
Last Post: deanhystad
  itertools and amazing speed Pedroski55 8 1,984 Nov-11-2022, 01:20 PM
Last Post: Gribouillis
  What happens to a <itertools.permutations object at 0x7fe3cc66af68> after it is read? Pedroski55 3 2,353 Nov-29-2020, 08:35 AM
Last Post: DeaD_EyE
  CPC File Format (Cartesian Perceptual Compression) - Can Python Convert / Handle Them PSKrieger 2 2,417 Nov-11-2020, 02:57 PM
Last Post: PSKrieger
  Making lists using itertools and eliminating duplicates. mike3891 2 2,189 Oct-26-2020, 05:39 PM
Last Post: bowlofred
  Python3 itertools.groupby printing the key august 1 2,043 Aug-17-2020, 05:46 AM
Last Post: bowlofred
  itertools.zip_shortest() fo unequal iterators Skaperen 10 6,580 Dec-27-2019, 12:17 AM
Last Post: Skaperen
  can itertools compact a list removing all of some value? Skaperen 6 3,099 Sep-02-2019, 03:19 AM
Last Post: Skaperen
  Help with itertools jarrod0987 1 1,782 Jun-10-2019, 02:41 AM
Last Post: Larz60+
  Step through a really large CSV file incrementally in Python bluethundr 6 6,834 May-07-2019, 08:46 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020