开发者

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

开发者 https://www.devze.com 2023-02-17 17:25 出处:网络
In Python, I am using list(itertools.permutations(\"0123456789\")), and I am receiving (I as expected) a list of tuples of singled character 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 ()).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号