In Python, I am using list(itertools.permutations("0123456789"))
, and I am receiving (I as expected) a list of tuples of singled character strings.
Is there a way to turn that result into a list of strings, without iterating over all 3628800 items?
If you want to do it without iterating over the whole list but rather lazily doing it as needed, you can use itertools.imap
:
itertools.imap(lambda x: "".join(x), itertools.permutations("0123456789"))
(note that I'm not using list()
on the result of permutations
here so it's as lazy as possible)
Or, as pointed out in the comments, a simple generator expression would work here as well:
("".join(x) for x in itertools.permutations("0123456789"))
itertools.imap
has the additional benefit of being able to apply the same function on lots of iterables with a convenient syntax (simply adding them as subsequent arguments), but that's not necessary for this particular usage as we only have one iterable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With