我正在创建一个二元函数,其中参数是单词列表,我想返回一个附加两个连续单词的新列表。
例如,如果这是文本:
text = '''
it was the best of times
it was the worst of times
it was the age of wisdom
it was the age of foolishness
'''
我希望输出是:
[('it', 'was'), ('was', 'the'), ('the', 'best'), ('best', 'of'), ('of', 'times'), ('times', 'it'), ('it', 'was'), ('was', 'the'), ('the', 'worst'), ('worst', 'of'), ('of', 'times'), ('times', 'it'), ('it', 'was'), ('was', 'the'), ('the', 'age'), ('age', 'of'), ('of', 'wisdom'), ('wisdom', 'it'), ('it', 'was'), ('was', 'the'), ('the', 'age'), ('age', 'of'), ('of', 'foolishness')]
我知道我需要循环遍历单词列表,但我不确定如何将连续元素附加在一起。 我应该注意,我不想使用任何库或 zip
函数来解决这个问题。
这是我所拥有的:
def bi_grams(tokens):
bigram = []
for word in tokens:
bigram.append([[word], [???]])
return bigram
???
部分是我陷入困境的地方。有什么建议吗?
最佳答案
使用zip
是最简单的方法之一:
bigram = list(zip(tokens, tokens[1:]))
关于python - 循环列表时如何附加连续元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58704176/