简体   繁体   English

如何将元组列表转换为没有逗号的字符串列表

[英]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.我尝试使用 .join 但它没有效果。

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.您需要join()每个排列。 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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM