You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用itertools构建字符串的递增前缀列表?

使用itertools生成累积走法字符串列表

首先把原始字符串拆分成单个国际象棋走法的列表:

import itertools

chess_str = "d4 d5 c4 e6 Nc3 Be7 Nf3 Nf6 Bg5 h6 Bf4 0-0 e3 Nbd7 g4 dxc4"
moves = chess_str.split()

接下来用itertools.accumulate函数生成逐步累加的字符串序列。这个函数会迭代处理输入的列表,每次将之前累积的结果和当前元素合并:

result = list(itertools.accumulate(moves, lambda prev, curr: f"{prev} {curr}"))

此时result就是你需要的列表,输出示例:

print(result)
# 输出: ["d4", "d4 d5", "d4 d5 c4", ..., "d4 d5 c4 e6 Nc3 Be7 Nf3 Nf6 Bg5 h6 Bf4 0-0 e3 Nbd7 g4 dxc4"]

关键说明

  • itertools.accumulate默认对元素执行加法操作,这里我们传入自定义的lambda函数,让它用空格连接前一个累积字符串和当前走法。
  • 最后将生成的迭代器转换成列表,就能得到从第一个走法开始逐步扩展的所有字符串集合。

内容的提问来源于stack exchange,提问作者SmallChess

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 11:36:14