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

Python中如何计算nCr并高效生成8人动作列表(附实现示例)

你可以直接使用Python标准库itertools.combinations实现组合(nCr)生成,无需手动编写大量重复条目,完整实现方案如下:

import itertools

# 配置士兵总数,此处为8人
SOLDIER_TOTAL = 8

actions = []
# 生成单士兵下哨动作
for soldier_id in range(SOLDIER_TOTAL):
    actions.append(('take one soldier off duty', soldier_id, 200))
# 生成双士兵下哨动作:自动计算8C2的所有组合
for group in itertools.combinations(range(SOLDIER_TOTAL), 2):
    actions.append(('take two soldiers off duty', group, 200))
# 生成三士兵下哨动作:自动计算8C3的所有组合
for group in itertools.combinations(range(SOLDIER_TOTAL), 3):
    actions.append(('take three soldiers off duty', group, 200))
# 生成替换士兵动作
for soldier_id in range(SOLDIER_TOTAL):
    actions.append(('replace soldier', soldier_id, 200))

上述代码生成的条目和你手动逐行编写的内容完全一致,后续如果需要调整士兵总人数,仅需修改SOLDIER_TOTAL的数值即可自动适配,无需改动其他逻辑。

内容的提问来源于stack exchange,提问作者Bryn Owen-Conway

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 23:06:02