【问题标题】:Get Tuple Index from itertool.combination list从 itertool.combination 列表中获取元组索引
【发布时间】:2021-10-20 14:35:53
【问题描述】:

大家早上好

我试图从 itertools.combination 函数生成的元组列表中插入索引 [0] 和索引 1 到变量 x 和 y 中

在这些链接'itertools.combinations' object is not subscriptable我发现组合中的对象不可下标,并且想知道是否有办法将单独的元组索引获取到函数中

a = [10,11,12,13,14,15]
b = combinations(a,2)

x= b[0]
y= b[1]

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)

【问题讨论】:

    标签: python list tuples combinations itertools


    【解决方案1】:

    itertools.combinations 返回一个生成器表达式。

    如果您想访问combinations 结果的索引,您必须使用list 来“使用”它:

    a = [10,11,12,13,14,15]
    b = list(combinations(a,2))
    
    x= b[0]
    y= b[1]
    
    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)
    

    【讨论】:

    • 嗨,谢谢你的建议,我刚刚做了,但是当我打印 x 和 Y 变量时,我得到: (10, 11) (10, 12) 当我将这些元组上传到的功能。例如,我需要:获取函数的下一个值: conditions = [df[f'sma_{10}'] > df[f'sma_{11}'], df[f'sma_{10}']
    • 好的,然后使用元组 x 并对其进行索引: [df[f'sma_{x[0]}'] > df[f'sma_{x[1]}'] , df[f'sma_{x[0]}']
    • 这对于a 中的任何大量索引都不实用,但它是处理一次性小问题的一种快速方法。
    猜你喜欢
    • 2021-04-25
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    相关资源
    最近更新 更多