【问题标题】:python sequence order with optional values具有可选值的python序列顺序
【发布时间】:2018-11-19 19:18:01
【问题描述】:

寻找一些帮助来生成一些代码,以根据永久和可选值创建所有可能的序列。示例...

序列保存在 MySQL Db 中,每个值都可以是可选的

所以有一个序列例如返回以下顺序

1,2,3,4

1 和 2 是必需的 3 & 4 是可选的

因此结果将返回以下序列可能性: [1,2], [1,2,3,4], [1,2,3], [1,2,4]

然后我可以将序列与那些序列进行比较,以确保接收到的序列与应有的顺序匹配。

感谢任何帮助。

【问题讨论】:

    标签: python sequence


    【解决方案1】:

    您实际上只对“可选”序列的超集感兴趣。您可以通过查找此超集并将其每个成员附加到“必需”列表来获得输出。

    from itertools import combinations
    
    required = [1, 2]
    optional = [3, 4]
    
    superset_optional = [combinations(optional, i) for i in range(len(optional) + 1)]
    for combinations in superset_optional:
        for comb in combinations :
            print(required + list(comb))
    
    #  [1, 2]
    #  [1, 2, 3]
    #  [1, 2, 4]
    #  [1, 2, 3, 4]
    

    【讨论】:

      猜你喜欢
      • 2022-11-18
      • 1970-01-01
      • 2018-09-08
      • 1970-01-01
      • 1970-01-01
      • 2023-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多