【发布时间】:2011-06-11 05:57:28
【问题描述】:
我想根据三个布尔值中的值设置一个变量。最直接的方式是 if 语句后跟一系列 elif:
if a and b and c:
name = 'first'
elif a and b and not c:
name = 'second'
elif a and not b and c:
name = 'third'
elif a and not b and not c:
name = 'fourth'
elif not a and b and c:
name = 'fifth'
elif not a and b and not c:
name = 'sixth'
elif not a and not b and c:
name = 'seventh'
elif not a and not b and not c:
name = 'eighth'
这有点尴尬,我想知道是否有更 Pythonic 的方式来处理这个问题。想到了几个想法。
-
字典破解:
name = {a and b and c: 'first', a and b and not c: 'second', a and not b and c: 'third', a and not b and not c: 'fourth', not a and b and c: 'fifth', not a and b and not c: 'sixth', not a and not b and c: 'seventh', not a and not b and not c: 'eighth'}[True]
我称其为 hack,因为我对其中 7 个键为 False 并相互覆盖并不太感兴趣。
-
和/或魔法
name = (a and b and c and 'first' or a and b and not c and 'second' or a and not b and c and 'third' or a and not b and not c and 'fourth' or not a and b and c and 'fifth' or not a and b and not c and 'sixth' or not a and not b and c and 'seventh' or not a and not b and not c and 'eighth')
这是可行的,因为 Python 的 ands 和 ors 返回要计算的最后一个值,但您必须知道这一点才能理解这段奇怪的代码。
这三个选项都不是很令人满意。你有什么推荐的?
【问题讨论】:
-
#2 的另一个缺点:当要映射到的值之一是虚假的(例如 0)时,它会失败。
-
+1 实用代码高尔夫 :)
-
似乎有些人将 'first'、'second' 视为任意占位符,而其他人则将它们视为您需要生成的实际字符串。我很好奇 - 你能解释一下吗?
-
它们是表示一般情况的占位符。
标签: python if-statement boolean