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

如何让Python排列组合脚本从指定序号(第91个)开始执行?

解决方法:跳过笛卡尔积的前90个元素

要让脚本从第91个笛卡尔积组合开始执行,核心思路是跳过迭代器的前90个元素——itertools.product返回的是迭代器,我们可以用两种简单方式实现需求:

方法1:使用itertools.islice切片迭代器

islice可以直接截取迭代器的指定范围,参数格式为islice(迭代器, 起始索引, 结束索引)。这里我们从索引90开始(对应第91个元素,因为索引从0开始),结束索引设为None表示取到迭代器末尾。

修改后的完整脚本:

import itertools

x1 = ['Hell', 'Frankenstein', 'Accident', 'Why', 'Okay']
x2 = ['BaldHead', 'Worms', 'SatansKingdom', 'Dinosaur', 'Coward']
x3 =['Dummer', 'DingDong', 'Chugwater', 'BoogerHole', 'Cut&Shoot']

# 生成笛卡尔积迭代器
y = itertools.product(x1, x2, x3)
# 跳过前90个元素,从第91个开始
y = itertools.islice(y, 90, None)

def produce_partially_set(wordlist):
    wordlist.insert(0, 'Boring')
    wordlist.insert(3, 'WhatCheer')
    wordlist.insert(5, 'Zap')
    wordlist.append('Fries')
    return wordlist

for i in y:
    # 直接将元组转为列表,替代join+split的冗余操作
    splitstrings = list(i)
    perms = produce_partially_set(splitstrings)
    seed = ' '.join(perms)
    print(seed)

方法2:手动调用next()跳过前90个元素

如果不想用islice,可以直接循环调用next()方法90次,手动消耗掉前90个元素:

import itertools

x1 = ['Hell', 'Frankenstein', 'Accident', 'Why', 'Okay']
x2 = ['BaldHead', 'Worms', 'SatansKingdom', 'Dinosaur', 'Coward']
x3 =['Dummer', 'DingDong', 'Chugwater', 'BoogerHole', 'Cut&Shoot']

y = itertools.product(x1, x2, x3)

# 手动跳过前90个元素
for _ in range(90):
    next(y)

def produce_partially_set(wordlist):
    wordlist.insert(0, 'Boring')
    wordlist.insert(3, 'WhatCheer')
    wordlist.insert(5, 'Zap')
    wordlist.append('Fries')
    return wordlist

for i in y:
    splitstrings = list(i)
    perms = produce_partially_set(splitstrings)
    seed = ' '.join(perms)
    print(seed)

额外优化点

原脚本中mystring = ' '.join(i)再splitstrings = mystring.split()是冗余操作——i本身就是包含三个元素的元组,直接转成列表list(i)即可得到相同结果,能节省字符串拼接和拆分的性能开销。

关于more_itertools.nth_permutation

这个函数用于生成排列的第n个结果,而你这里是笛卡尔积(并非排列),因此完全不适用,无需考虑该方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 06:32:53