Skip to main content
 首页 » 编程设计

python之循环列表时如何追加顺序元素

2024年08月12日33bjzhanghao

我正在创建一个 bigram 函数,其中参数是一个单词列表,我想返回一个附加两个连续单词的新列表。

例如,如果这是文本:

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:]))