python ternary operator with assignment

前端 未结 6 881
眼角桃花
眼角桃花 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:30

    For those interested in the ternary operator (also called a conditional expression), here is a way to use it to accomplish half of the original goal:

    q = d[x] if x in d else {}

    The conditional expression, of the form x if C else y, will evaluate and return the value of either x or y depending on the condition C. The result will then be assigned to q.

提交回复
热议问题