我有一个包含字符串的元组列表 例如:
[('this', 'is', 'a', 'foo', 'bar', 'sentences')
('is', 'a', 'foo', 'bar', 'sentences', 'and')
('a', 'foo', 'bar', 'sentences', 'and', 'i')
('foo', 'bar', 'sentences', 'and', 'i', 'want')
('bar', 'sentences', 'and', 'i', 'want', 'to')
('sentences', 'and', 'i', 'want', 'to', 'ngramize')
('and', 'i', 'want', 'to', 'ngramize', 'it')]
现在我希望将每个字符串连接到一个元组中以创建一个空格分隔的字符串列表。 我使用了以下方法:
NewData=[]
for grams in sixgrams:
NewData.append( (''.join([w+' ' for w in grams])).strip())
它工作得很好。
但是,我拥有的列表有超过一百万个元组。所以我的问题是这种方法是否足够有效,或者是否有更好的方法来做到这一点。 谢谢。
最佳答案
对于大量数据,您应该考虑是否需要将它们全部保存在一个列表中。如果您一次处理每一个,则可以创建一个生成器,该生成器将生成每个连接的字符串,但不会让它们全部占用内存:
new_data = (' '.join(w) for w in sixgrams)
如果您也可以从生成器中获取原始元组,那么您也可以避免将 sixgrams
列表放在内存中。
关于python - 在python的列表中连接元组的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20736917/