python - 在python的列表中连接元组的元素

标签 python string list tuples concatenation

我有一个包含字符串的元组列表 例如:

[('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/

相关文章:

python - 如何读取逗号旁边有双引号的 csv 文件

python - 更新列表中的元组

c# - 将 appsetting 值从字符串解析为字符串数组

python - 我如何通过嵌套列表理解来实现这一点?

list - 如何将两个列表 append 在一起?方案

python - 使用pika,是否可以读取rabbitmq绑定(bind)参数?

android - 我在哪里可以运行未编译的脚本?

python - 更改 Halide 输出缓冲区布局

java - 将单词放入字符串数组中

swift - 为什么将 Double 转换为 Int 不会在 Swift 中返回可选的 Int?