[英]Is there a Python shortcut for variable checking and assignment?
I'm finding myself typing the following a lot (developing for Django, if that's relevant): 我发现自己经常输入以下内容(如果相关,请为Django开发):
if testVariable then:
myVariable = testVariable
else:
# something else
Alternatively, and more commonly (ie building up a parameters list) 或者,更常见的是(即建立参数列表)
if 'query' in request.POST.keys() then:
myVariable = request.POST['query']
else:
# something else, probably looking at other keys
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 = assign_if_exists(testVariable)
吗?
Assuming you want to leave myVariable untouched to its previous value in the "not exist" case, 假设您希望在“不存在”的情况下保持myVariable不变为其先前的值,
myVariable = testVariable or myVariable
deals with the first case, and 处理第一种情况,并且
myVariable = request.POST.get('query', myVariable)
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.
不过,两者都与“ exist”没有多大关系(这几乎不是Python概念;-):第一个与true或false有关,第二个与集合中是否存在键有关。
The first instance is stated oddly... Why set a boolean to another boolean? 第一个实例奇怪地陈述了...为什么将一个布尔值设置为另一个布尔值?
What you may mean is to set myVariable to testVariable when testVariable is not a zero length string or not None or not something that happens to evaluate to False. 您可能的意思是,当testVariable不是长度为零的字符串或不是None或没有某种值求为False时,将myVariable设置为testVariable。
If so, I prefer the more explicit formulations 如果是这样,我倾向于更明确的表述
myVariable = testVariable if bool(testVariable) else somethingElse
myVariable = testVariable if testVariable is not None else somethingElse
When indexing into a dictionary, simply use get
. 索引到字典时,只需使用
get
。
myVariable = request.POST.get('query',"No Query")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.