python ternary operator with assignment

前端 未结 6 889
眼角桃花
眼角桃花 2021-01-22 23:01

I am new to python. I\'m trying to write this

if x not in d:
    d[x] = {}
q = d[x]

in a more compact way using the ternary operator

         


        
6条回答
  •  伪装坚强ぢ
    2021-01-22 23:17

    The conditional operator in Python is used for expressions only, but assignments are statements. You can use

    q = d.setdefault(x, {})
    

    to get the desired effect in this case. See also the documentation of dict.setdefault().

提交回复
热议问题