在python中连接列表中元组的元素
我有一个包含字符串的元组列表 例如:在python中连接列表中元组的元素,python,string,list,tuples,concatenation,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
[('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())
这是非常好的工作
然而,我的列表有超过一百万个元组。所以我的问题是,这种方法是否足够有效,或者是否有更好的方法来做到这一点。
谢谢。列表将创建临时字符串。只需使用
''。加入
>>> words_list = [('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')]
>>> new_list = []
>>> for words in words_list:
... new_list.append(' '.join(words)) # <---------------
...
>>> new_list
['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']
你可以像这样高效地完成这项工作
joiner = " ".join
print map(joiner, sixgrams)
joiner = " ".join
print [joiner(words) for words in sixgrams]
我们仍然可以使用这样的列表理解来提高性能
joiner = " ".join
print map(joiner, sixgrams)
joiner = " ".join
print [joiner(words) for words in sixgrams]
性能比较表明,上述列表理解解决方案略快于其他两种解决方案
from timeit import timeit
joiner = " ".join
def mapSolution():
return map(joiner, sixgrams)
def comprehensionSolution1():
return ["".join(words) for words in sixgrams]
def comprehensionSolution2():
return [joiner(words) for words in sixgrams]
print timeit("mapSolution()", "from __main__ import joiner, mapSolution, sixgrams")
print timeit("comprehensionSolution1()", "from __main__ import sixgrams, comprehensionSolution1, joiner")
print timeit("comprehensionSolution2()", "from __main__ import sixgrams, comprehensionSolution2, joiner")
我的机器上的输出
1.5691678524
1.66710209846
1.47555398941
性能提高很可能是因为,我们不必每次都从空字符串创建连接函数
<强>编辑:< /强>虽然我们可以像这样提高性能,但是大多数的Python方式是使用类似于.I/P>< P>的生成器,对于很多数据,你应该考虑是否需要将其全部保存在列表中。如果一次处理每个字符串,则可以创建一个生成器,该生成器将生成每个连接的字符串,但不会占用内存:
new_data = (' '.join(w) for w in sixgrams)
如果还可以从生成器中获取原始元组,那么也可以避免在内存中出现sixgrams
列表