Python elegant assignment based on True/False values

后端 未结 11 1625
日久生厌
日久生厌 2021-01-31 09:32

I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs:

if a a         


        
11条回答
  •  甜味超标
    2021-01-31 09:52

    You can think of a, b, and c as three bits that when put together form a number between 0 and 7. Then, you can have an array of the values ['first', 'second', ... 'eighth'] and use the bit value as an offset into the array. This would just be two lines of code (one to assemble the bits into a value from 0-7, and one to lookup the value in the array).

    Here's the code:

    nth = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
    nth[(a and 4 or 0) | (b and 2 or 0) | (c and 1 or 0)]
    

提交回复
热议问题