我来自PHP背景,想知道是否有办法在Python中执行此操作。
在PHP中你可以像这样一石二鸟:
而不是:
if(getData()){
$data = getData();
echo $data;
}
我可以这样做:
if($data = getData()){
echo $data;
}
您检查getData()
是否存在,如果存在,则将其分配给一个语句中的变量。
我想知道在Python中是否有办法做到这一点?所以不要这样做:
if request.GET.get('q'):
q = request.GET.get('q')
print q
避免两次写request.GET.get('q')
。
答案 0 :(得分:25)
可能不完全是你在想什么,但是......
q = request.GET.get('q')
if q:
print q
此?
答案 1 :(得分:25)
请参阅我8年之久的食谱here来完成这项任务。
# In Python, you can't code "if x=foo():" -- assignment is a statement, thus
# you can't fit it into an expression, as needed for conditions of if and
# while statements, &c. No problem, if you just structure your code around
# this. But sometimes you're transliterating C, or Perl, or ..., and you'd
# like your transliteration to be structurally close to the original.
#
# No problem, again! One tiny, simple utility class makes it easy...:
class DataHolder:
def __init__(self, value=None): self.value = value
def set(self, value): self.value = value; return value
def get(self): return self.value
# optional but handy, if you use this a lot, either or both of:
setattr(__builtins__,'DataHolder',DataHolder)
setattr(__builtins__,'data',DataHolder())
# and now, assign-and-set to your heart's content: rather than Pythonic
while 1:
line = file.readline()
if not line: break
process(line)
# or better in modern Python, but quite far from C-like idioms:
for line in file.xreadlines():
process(line)
# you CAN have your C-like code-structure intact in transliteration:
while data.set(file.readline()):
process(data.get())
答案 2 :(得分:9)
Alex's answer的变体:
class DataHolder:
def __init__(self, value=None, attr_name='value'):
self._attr_name = attr_name
self.set(value)
def __call__(self, value):
return self.set(value)
def set(self, value):
setattr(self, self._attr_name, value)
return value
def get(self):
return getattr(self, self._attr_name)
save_data = DataHolder()
用法:
if save_data(get_input()):
print save_data.value
或者如果您更喜欢其他界面:
if save_data.set(get_input()):
print save_data.get()
我觉得这有助于在if-elif-elif-elif等结构中测试一系列正则表达式,如this SO question中所示:
import re
input = u'test bar 123'
save_match = DataHolder(attr_name='match')
if save_match(re.search('foo (\d+)', input)):
print "Foo"
print save_match.match.group(1)
elif save_match(re.search('bar (\d+)', input)):
print "Bar"
print save_match.match.group(1)
elif save_match(re.search('baz (\d+)', input)):
print "Baz"
print save_match.match.group(1)
答案 3 :(得分:2)
q = request.GET.get('q')
if q:
print q
else:
# q is None
...
没有办法一次性完成任务和条件......
答案 4 :(得分:1)
如果get()在不存在的情况下抛出异常,则可以执行
try:
q = request.GET.get('q')
print q
except :
pass
答案 5 :(得分:1)
PEP 572引入了分配表达式。从Python 3.8起,您可以编写:
if q := request.GET.get('q'):
print q
以下是PEP Syntax and semantics部分的一些示例:
# Handle a matched regex
if (match := pattern.search(data)) is not None:
# Do something with match
# A loop that can't be trivially rewritten using 2-arg iter()
while chunk := file.read(8192):
process(chunk)
# Reuse a value that's expensive to compute
[y := f(x), y**2, y**3]
# Share a subexpression between a comprehension filter clause and its output
filtered_data = [y for x in data if (y := f(x)) is not None]
答案 6 :(得分:0)
嗯,这将是一种方式
q = request.GET.get('q')
if q:
print q
一个简短的方式(但不是优越的,因为要求打印无效)方式
print request.GET.get('q') or '',
答案 7 :(得分:0)
config_hash = {}
tmp_dir = ([config_hash[x] for x in ["tmp_dir"] if config_hash.has_key(x)] or ["tmp"])[0]
print tmp_dir
config_hash["tmp_dir"] = "cat"
tmp_dir = ([config_hash[x] for x in ["tmp_dir"] if config_hash.has_key(x)] or ["tmp"])[0]
print tmp_dir
答案 8 :(得分:0)
一种可行的方法,无需先设置变量,可以像:
if (lambda x: globals().update({'q':x}) or True if x else False)(request.GET.get('q')):
print q
..它只是为了好玩 - 不应该使用这种方法,因为它是丑陋的黑客,乍一看很难理解,它创建/覆盖全局变量(只有在满足条件的情况下)
答案 9 :(得分:0)