是否存在用于变量检查和赋值的Python快捷方式? [英] Is there a Python shortcut for variable checking and assignment?
问题描述
我发现自己经常键入以下内容(如果相关的话,请为Django开发):
I'm finding myself typing the following a lot (developing for Django, if that's relevant):
if testVariable then:
myVariable = testVariable
else:
# something else
或者更常见的方式(即建立参数列表)
Alternatively, and more commonly (i.e. building up a parameters list)
if 'query' in request.POST.keys() then:
myVariable = request.POST['query']
else:
# something else, probably looking at other keys
是否有我不知道的快捷方式可以简化此操作?带有某种逻辑 myVariable = Assign_if_exists(testVariable)
?
Is there a shortcut I just don't know about that simplifies this? Something with the kind of logic myVariable = assign_if_exists(testVariable)
?
推荐答案
假设您希望在不存在"的情况下将myVariable保持其先前值不变,
Assuming you want to leave myVariable untouched to its previous value in the "not exist" case,
myVariable = testVariable or myVariable
处理第一种情况,
myVariable = request.POST.get('query', myVariable)
与第二个交易.不过,两者都与"exist"无关(这几乎不是Python的概念;-):第一个与true或false有关,第二个与集合中是否存在键有关.
deals with the second one. Neither has much to do with "exist", though (which is hardly a Python concept;-): the first one is about true or false, the second one about presence or absence of a key in a collection.
这篇关于是否存在用于变量检查和赋值的Python快捷方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!