简体   繁体   中英

Permutations and removing tuples

Here's my code:

import itertools
def permutations(string):
    if len(string) <= 1:
      return string
    return itertools.permutations(string)

If 'ab' is input, it returns [('a', 'b'), ('b', 'a')]

Is there any way I can combine the tuple items and then change the tuple into a list item such that it returns: ['ab', 'ba'] ?

strings are seen as iterables, and combined into tuples by itertools.permutations .

To convert them back as strings, just use str.join on the tuples (would work on a longer permutation):

["".join(x) for x in [('a', 'b'), ('b', 'a')]]

in your case:

["".join(x) for x in itertools.permutations(string)]
 [a+b for a,b in itertools.permutations(string)]

map

 map(lambda(x):''.join(x), itertools.permutations(string))

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