简体   繁体   中英

How to turn the result (in python) of itertools.permutations(“0123456789”) into list of strings

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

Turning it into a list iterates over the whole thing. You can turn it into a list with a list comprehension, which will be better than turning it into a list then iterating over all the items of the list:

[''.join(item) for item in itertools.permutations('0123456789')]

If you don't need to end up with a list, a generator expression will suffice (replace [] with () ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM