Python 有变量检查和赋值的快捷方式吗?
我发现自己经常输入以下内容(为 Django 开发,如果相关的话):
if testVariable then:
myVariable = testVariable
else:
# something else
或者,更常见的是(即构建参数列表)
if 'query' in request.POST.keys() then:
myVariable = request.POST['query']
else:
# something else, probably looking at other keys
是否有一个我不知道的快捷方式可以简化此操作? 具有某种逻辑 myVariable = allocate_if_exists(testVariable)
的东西?
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
Is there a shortcut I just don't know about that simplifies this? Something with the kind of logic myVariable = assign_if_exists(testVariable)
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设您希望在“不存在”的情况下让 myVariable 保持其先前的值不变,
处理第一种情况,然后
处理第二种情况。 不过,两者都与“存在”没有太大关系(这几乎不是 Python 概念;-):第一个是关于 true 或 false,第二个是关于集合中键的存在或不存在。
Assuming you want to leave myVariable untouched to its previous value in the "not exist" case,
deals with the first case, and
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.
第一个实例的表述很奇怪......为什么将一个布尔值设置为另一个布尔值?
您可能的意思是,当 testVariable 不是零长度字符串或不是 None 或不是恰好评估为 False 的内容时,将 myVariable 设置为 testVariable。
如果是这样,我更喜欢更明确的表述。
当索引到字典时,只需使用
get
即可。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.
If so, I prefer the more explicit formulations
When indexing into a dictionary, simply use
get
.