Python elegant assignment based on True/False values

后端 未结 11 1609
日久生厌
日久生厌 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:48

    Here is a truth table approach:

    lookup = {'000': 'eighth',
              '001': 'seventh',
              '010': 'sixth',
              '011': 'fifth',
              '100': 'fourth',
              '101': 'third',
              '110': 'second',
              '111': 'first'}
    
    def key(a, b, c):
        return ''.join([str(a),str(b),str(c)])
    
    name = lookup[key(0,1,1)]
    

提交回复
热议问题