Python conditional assignment operator

前端 未结 10 2029
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 18:03

Does a Python equivalent to the Ruby ||= operator (\"set the variable if the variable is not set\") exist?

Example in Ruby :

 variable_n         


        
10条回答
  •  情书的邮戳
    2020-12-08 18:43

    I think what you are looking for, if you are looking for something in a dictionary, is the setdefault method:

    (Pdb) we=dict()
    (Pdb) we.setdefault('e',14)
    14
    (Pdb) we['e']
    14
    (Pdb) we['r']="p"
    (Pdb) we.setdefault('r','jeff')
    'p'
    (Pdb) we['r']
    'p'
    (Pdb) we[e]
    *** NameError: name 'e' is not defined
    (Pdb) we['e']
    14
    (Pdb) we['q2']
    

    *** KeyError: 'q2' (Pdb)

    The important thing to note in my example is that the setdefault method changes the dictionary if and only if the key that the setdefault method refers to is not present.

提交回复
热议问题