Python:迭代一系列列表以创建自定义配置以加载到我的模型输入中

问题描述 投票:0回答:1

我无法找到一种优雅的方法来迭代我的模型输入敏感度案例来创建可以传递到我的模型中进行敏感度分析的配置。

相当容易完成,但我一直在努力。

我有一个需要一系列输入的模型。为了更深入地了解我正在建模的技术,我想运行 P10、P90 敏感性分析。

设置: 我的模型输入敏感案例位于 p10、p50 和 p90 的命名元组中:

Sensitivity_Case = namedtuple('Sensitivity_Case', [
    'a',  
    'b',  
    'c',  
])

#p50 case  
p50 = Sensitivity_Case(  
    5,  
    50,  
    'medium',  
)

#p10 case
p10 = Sensitivity_Case(
    1,
    5,
    'low',
)


#p90 case
p90 = Sensitivity_Case(
    10,
    500,
    'high',
)

为了获得用于敏感性分析的正确数据,我需要通过一次操作一个变量来运行我的模型,同时将所有其他变量保持在 p50(基本)情况。为此,我想创建一系列配置(然后将输入循环到我的模型中),其外观如下“

config1 = [**a.p10**, b.p50, c.p50]
config2 = [**a.p90**, b.p50, c.p50]
config3 = [a.p50, **b.p10**, c.p50]
config4 = [a.p50, **b.p90**, c.p50]
config5 = [a.p50, b.p50, **c.p10**]
config6 = [a.p50, b.p50, **c.p90**]

显然,如果构建这些配置的任何迭代器都能够灵活地自适应地获取输入列表并计算出(通过 len() 或其他方式)对敏感案例列表中的 n 个项目进行所需的尽可能多的配置排列,那将是更好的选择。否则我就手动进行配置(这对于 100 个变量来说会很费力)

我对 python 和一般编码相当陌生。我相信我想做的〜应该〜是 下面是尝试制作配置生成器的第一次尝试,但存在明显的缺陷。主要缺陷是它无法生成 config2 之后的配置。该函数还创建一个中间配置(所有变量 p50s 的基本配置)。

def generate_combinations(lists):
    result = []

    # all lists have the same length
    list_length = len(lists[0])

    for i in range(list_length):
        current_combination = [lists[0][i]] + [lists[j][1] for j in range(1, len(lists))]
        result.append(current_combination)

    return result

# Example usage:
list1 = [a.p10, a.p50, a.p90]
list2 = [b.p10, b.p50, b.p90]
list3 = [c.p10, c.p50, c.p90]

combined_lists = generate_combinations([list1, list2, list3])

for combination in combined_lists:
    print(combination)
python tuples
1个回答
0
投票

您可以使用

itertools.product
函数生成敏感案例的所有可能组合。

© www.soinside.com 2019 - 2024. All rights reserved.