python ternary operator with assignment

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

    The reason that else (d[x] = {}) is a syntax error is that in Python, assignment is a statement. But the conditional operator expects expressions, and while every expression can be a statement, not every statement is an expression.

提交回复
热议问题