字典的python布尔键

2024-05-14 00:30:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用一组布尔值作为字典的键,所以(weather==sunny and temp==warm)应该是11或True,而(weather==sunny and weather==cold)应该是10,并且(weather==cloudy and weather==cold)应该是00,False应该是00,在这里,衣服应该是11:“短裤”,牛仔裤,夹克应该是00?我想它可能需要位操作,我正试图保持这个尽可能快的操作时间。


Tags: andfalsetrue字典tempweathercloudywarm
2条回答

如果您实际上不需要对单个条件执行按位操作(即,您不需要和/或两个条件一起执行),则只使用一个布尔元组作为键可能更简单:

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

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

sunny = 0
cloudy = 1
cold = 2
clothing = { (cold|cloudy) :"shorts", cold:"jeans", sunny:"jacket"}

weather = something()

print(clothing[ weather & (cold|cloudy) ])

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

相关问题 更多 >