如何将列表中的元素合并在一起? [英] How do i merge elements in a list together?
本文介绍了如何将列表中的元素合并在一起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个句子列表,我想将它们合并在一起以创建一个完整的列表.
I have this list of sentences and I want to merge them together to create one whole list.
test = [['Hello my name is Py. How are you today?'],['The world is a great place. Another sentence.']]
如何合并元素以创建它?
How do I merge the elements to create this?
test = ['Hello my name is Py. How are you today? The world is a great place. Another sentence.']
或
test = 'Hello my name is Py. How are you today? The world is a great place. Another sentence.'
谢谢
推荐答案
You can use itertools.chain to chain the element from each sublist, calling str.join on the chain object to create a single string.
test = [['Hello my name is Py. How are you today?'],['The world is a great place. Another sentence.']]
from itertools import chain
print(" ".join(chain.from_iterable(test)))
Hello my name is Py. How are you today? The world is a great place. Another sentence
或者仅使用联接:
print(" ".join(["".join(sub) for sub in test]))
Hello my name is Py. How are you today? The world is a great place. Another sentence.
如果每个子列表中只有一个字符串,则只需索引:
If you only have a single sting in each sublist just index:
print(" ".join([sub[0] for sub in test]))
Hello my name is Py. How are you today? The world is a great place. Another sentence.
要获取列表,只需将联接包装在列表中即可:
To get a list just wrap the join in a list:
print([" ".join([sub[0] for sub in test])])
['Hello my name is Py. How are you today? The world is a great place. Another sentence.']
如果每个子列表中都有很多子字符串,那么链将是最有效的解决方案.
If you have a lot of substrings in each sublist then chain will be the most efficient solution.
这篇关于如何将列表中的元素合并在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文