简体   繁体   English

如何将元组列表转换为单个字符串

[英]How to convert a list of tuples into a single string

I have a list of tuples, where all emlements in the tuples are strings. 我有一个元组列表,其中元组中的所有元素都是字符串。 It could look like this: 它可能看起来像这样:

my_list = [('a', 'b', 'c'), ('d', 'e')]

I want to convert this to a string so it would look like 'abcd e'. 我想将其转换为字符串,因此它看起来像'abcd e'。 I can use ' '.join( ... ) but I'm unsure of what argument I should use. 我可以使用''。join(...)但我不确定我应该使用什么参数。

You can flatten the list, then use join: 您可以展平列表,然后使用join:

>>> import itertools
>>> ' '.join(itertools.chain(*my_list))
'a b c d e'

or with list comprehension: 或列表理解:

>>> ' '.join([i for sub in my_list for i in sub])
'a b c d e'
>>> my_list = [('a', 'b', 'c'), ('d', 'e')]
>>> ' '.join(' '.join(i) for i in my_list)
'a b c d e'

You can use a list comprehension which will iterate over the tuples and then iterate over each tuple, returning the item for joining. 您可以使用列表推导来迭代元组,然后迭代每个元组,返回项目以进行连接。

my_list = [('a', 'b', 'c'), ('d', 'e')]

s = ' '.join([item for tup in my_list for item in tup])

The list comprehension is equivalent to: 列表理解等同于:

a = []
for tup in my_list:
    for item in tup:
        a.append(item)
my_list = [('a', 'b', 'c'), ('d', 'e')]

L = []

for x in my_list:
    L.extend(x) 

print ' '.join(L)


output:
'a b c d e'
my_list = [('a', 'b', 'c'), ('d', 'e')]
print "".join(["".join(list(x)) for x in my_list])

Try this. 尝试这个。

List comprehension is the best one liner solution to your question :- 列表理解是您问题的最佳解决方案 : -

my_list = [('a', 'b', 'c'), ('d', 'e')]
s = ' '.join([elem for item in my_list for elem in item])

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

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