Reputation: 159
How do I convert the list of permutations into something that simply is:
['HELLO SAMPLE STRING SET', 'HELLO SAMPLE SET STRING' ...]
i.e. for each item in the list of tuples, I would like to make the separator a space rather than comma, and also make it a simple string, not a tuple?
I have tried to use .join but it hasn't been effective.
Example:
strings = ['HELLO', 'SAMPLE', 'STRING', 'SET']
permutations_str = list(permutations(strings))
This produces the below, but would like it as above.
[('HELLO', 'SAMPLE', 'STRING', 'SET'), ('HELLO', 'SAMPLE', 'SET', 'STRING'), ('HELLO', 'STRING', 'SAMPLE', 'SET'), ('HELLO', 'STRING', 'SET', 'SAMPLE'), ('HELLO', 'SET', 'SAMPLE', 'STRING'), ('HELLO', 'SET', 'STRING', 'SAMPLE'), ('SAMPLE', 'HELLO', 'STRING', 'SET'), ('SAMPLE', 'HELLO', 'SET', 'STRING'), ('SAMPLE', 'STRING', 'HELLO', 'SET'), ('SAMPLE', 'STRING', 'SET', 'HELLO'), ('SAMPLE', 'SET', 'HELLO', 'STRING'), ('SAMPLE', 'SET', 'STRING', 'HELLO'), ('STRING', 'HELLO', 'SAMPLE', 'SET'), ('STRING', 'HELLO', 'SET', 'SAMPLE'), ('STRING', 'SAMPLE', 'HELLO', 'SET'), ('STRING', 'SAMPLE', 'SET', 'HELLO'), ('STRING', 'SET', 'HELLO', 'SAMPLE'), ('STRING', 'SET', 'SAMPLE', 'HELLO'), ('SET', 'HELLO', 'SAMPLE', 'STRING'), ('SET', 'HELLO', 'STRING', 'SAMPLE'), ('SET', 'SAMPLE', 'HELLO', 'STRING'), ('SET', 'SAMPLE', 'STRING', 'HELLO'), ('SET', 'STRING', 'HELLO', 'SAMPLE'), ('SET', 'STRING', 'SAMPLE', 'HELLO')]
Upvotes: 1
Views: 59
Reputation: 92440
You need to join()
each of the permutations. You can do that with a simple comprehension like:
from itertools import permutations
strings = ['HELLO', 'SAMPLE', 'STRING', 'SET']
results = [" ".join(s) for s in permutations(strings)]
results:
['HELLO SAMPLE STRING SET',
'HELLO SAMPLE SET STRING',
'HELLO STRING SAMPLE SET',
'HELLO STRING SET SAMPLE',
'HELLO SET SAMPLE STRING',
...
'SET STRING SAMPLE HELLO']
Upvotes: 2