【问题标题】:python boolean key for a dictionary字典的python布尔键
【发布时间】:2013-04-21 19:56:20
【问题描述】:

我想使用一组布尔值作为字典的键,因此 (天气 == 晴天和温度 == 温暖) 将是 11 或 True,True 而 (天气 == 晴天和天气 == 寒冷) 将是10 and (weather == cloudy and weather == cold) True,False 将是 00 where 服装 = {11:"shorts", 10:"jeans", 00:"jacket"} 有没有办法做到这一点?我认为它可能需要位操作,并且我正在尝试尽可能快地保持操作时间。

【问题讨论】:

    标签: python dictionary boolean boolean-logic


    【解决方案1】:

    如果您实际上不需要对单个条件执行按位运算(即,您不需要将两个条件与/或),则仅使用布尔值元组作为键可能更简单:

    clothing = {
        (True, True): "shorts",
        (True, False): "jeans",
        (False, False): "jacket"
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用按位或 (|) 运算符:

      sunny = 0
      cloudy = 1
      cold = 2
      clothing = { (cold|cloudy) :"shorts", cold:"jeans", sunny:"jacket"}
      
      weather = something()
      
      print(clothing[ weather & (cold|cloudy) ])
      

      但@BrenBarn 建议的元组版本更好。

      【讨论】:

        猜你喜欢
        • 2018-04-26
        • 2019-02-10
        • 2017-10-10
        • 2017-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-22
        相关资源
        最近更新 更多