如何获取itertools.combination生成的元组列表的索引并赋值给变量
itertools.combinations 返回的是惰性迭代器对象,本身没有实现下标访问的相关方法,要获取生成的二元组的元素,可以按你的使用场景选择以下两种方案:
- 方案1:直接迭代迭代器(适合批量处理所有组合,内存占用更低)
如果你的需求是对所有两两组合都生成对应的sma交叉列,直接迭代combinations对象即可,每次迭代会返回一个二元组,可以直接解包赋值给x、y:
import itertools import numpy as np import pandas as pd a = [10,11,12,13,14,15] for x, y in itertools.combinations(a, 2): conditions = [ df[f'sma_{x}'] > df[f'sma_{y}'], df[f'sma_{x}'] < df[f'sma_{y}'] ] choices = [1, -1] df[f'sma_{x} & sma_{y}'] = np.select(conditions, choices, default=0)
这种方式不需要将所有组合一次性加载到内存,当a的长度较大、组合数量较多时性能更优。
- 方案2:转列表后下标访问(适合需要随机获取指定位置组合的场景)
如果你确实需要获取指定位置的组合,先将迭代器转换为列表,即可正常使用下标访问:
import itertools a = [10,11,12,13,14,15] b = list(itertools.combinations(a, 2)) # 示例:获取第1个组合的两个值,下标从0开始计数 x, y = b[0] # 后续逻辑保持不变 conditions = [ df[f'sma_{x}'] > df[f'sma_{y}'], df[f'sma_{x}'] < df[f'sma_{y}'] ] choices = [1, -1] df[f'sma_{x} & sma_{y}'] = np.select(conditions, choices, default=0)
你之前代码报错是因为直接对combinations迭代器做下标操作,而迭代器本身不支持该操作,转换为列表后即可解决。
内容的提问来源于stack exchange,提问作者holguinmora
相关产品推荐
相关产品推荐

