python ternary operator with assignment

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

    In Python, assignments cannot occur in expressions, therefore you can't write code like a = (b = c).

    You're looking for setdefault:

    q = d.setdefault(x, {})
    

    Alternative, use a defaultdict.

提交回复
热议问题