Python elegant assignment based on True/False values

后端 未结 11 1678
日久生厌
日久生厌 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 10:04

    I'd go for the list/bits solution of @OscarRyz, @Clint and @Sven, but here's another one:

    
    S1 = frozenset(['first', 'second', 'third', 'fourth'])
    S2 = frozenset(['first', 'second', 'fifth', 'sixth'])
    S3 = frozenset(['first', 'third', 'fifth', 'seventh'])
    last = 'eighth'
    empty = frozenset([])

    def value(a, b, c): for r in (a and S1 or empty) & (b and S2 or empty) & (c and S3 or empty): return r return last

提交回复
热议问题