如何将下面的二元组合并为单个字符串?
_bigrams=['the school', 'school boy', 'boy is', 'is reading']
_split=(' '.join(_bigrams)).split()
_newstr=[]
_filter=[_newstr.append(x) for x in _split if x not in _newstr]
_newstr=' '.join(_newstr)
print _newstr
Output:'the school boy is reading'
....它是所需的输出,但鉴于我的数据量很大,该方法太长并且效率不高。其次,该方法不支持最终字符串中的重复单词,即'the school boy is reading, is he?'
。仅其中之一'is'
在这种情况下,将允许出现在最终字符串中。
关于如何使这项工作变得更好有什么建议吗?谢谢。
# Multi-for generator expression allows us to create a flat iterable of words
all_words = (word for bigram in _bigrams for word in bigram.split())
def no_runs_of_words(words):
"""Takes an iterable of words and returns one with any runs condensed."""
prev_word = None
for word in words:
if word != prev_word:
yield word
prev_word = word
final_string = ' '.join(no_runs_of_words(all_words))
这利用了生成器来延迟计算,并且不会同时将整组单词保留在内存中,直到生成一个最终字符串。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)