python - 循环列表时如何附加连续元素?

标签 python

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

例如,如果这是文本:

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/

相关文章:

python - 库未加载 : libssl. 1.0.0.dylib 原因:找不到图像

python - 保存本地日期时间将时间偏移 4 分钟

python - 删除列表中的重复项

python - 如何使用 pandas 在一个命令行中连续写入多个值

python - Pandas - 将具有多个索引的字典映射到列

python - 在 Raspberry Pi 重启时运行 Python3 模块

python - 在 django 自定义用户模型上添加新用户时,"' NoneType ' object is not iterable"

python - OR 逻辑与 Django-filter

python - 将 OpenCV 获取的图像保存到另一台计算机上(使用 FTP 或其他方式)

python - 向 seaborn 中的每个子图添加文本