How to get all permutations of a string as a list of strings (instead of a list of tuples)?

The goal was to create a list of all possible combinations of certain letters in the word ... Which is good, except that now it ends with a list of tuples with too many quotes and commas.

import itertools

mainword = input(str("Enter a word: "))
n_word = int((len(mainword)))

outp = (list(itertools.permutations(mainword,n_word)))

What I want:

[yes, yse, eys, esy, sye, sey]

What I get:

[('y', 'e', 's'), ('y', 's', 'e'), ('e', 'y', 's'), ('e', 's', 'y'), ('s', 'y', 'e'), ('s', 'e', 'y')]

I think I need to remove all brackets, quotes and commas.

I tried:

def remove(old_list, val):
  new_list = []
  for items in old_list:
    if items!=val:
        new_list.append(items)
  return new_list
  print(new_list)

where I just run the function a few times. But that does not work.

+4
source share
3 answers

You can use the join function. Below code works fine. I also attach a screenshot.

import itertools

mainword = input(str("Enter a word: "))
n_word = int((len(mainword)))

outp = (list(itertools.permutations(mainword,n_word)))

for i in range(0,6):
  outp[i]=''.join(outp[i])

print(outp)

enter image description here

+2
source

You can recombine these tuples with understanding, for example:

The code:

new_list = [''.join(d) for d in old_list]

Security Code:

data = [
    ('y', 'e', 's'), ('y', 's', 'e'), ('e', 'y', 's'),
    ('e', 's', 'y'), ('s', 'y', 'e'), ('s', 'e', 'y')
]

data_new = [''.join(d) for d in data]
print(data_new)

:

['yes', 'yse', 'eys', 'esy', 'sye', 'sey']
+6

str.join() , . :

>>> from itertools import permutations
>>> word = 'yes'

>>> [''.join(w) for w in permutations(word)]
['yes', 'yse', 'eys', 'esy', 'sye', 'sey']

map(), :

>>> list(map(''.join, permutations(word)))
['yes', 'yse', 'eys', 'esy', 'sye', 'sey']
+4
source

Source: https://habr.com/ru/post/1693479/


All Articles