简体   繁体   中英

How to convert list of tuples into list of strings with no commas

How do I convert the list of permutations into something that simply is:

['HELLO SAMPLE STRING SET', 'HELLO SAMPLE SET STRING' ...]

ie 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')]

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']

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