giv*_*ivp 41 python dictionary if-statement
我来自PHP背景,想知道是否有办法在Python中执行此操作.
在PHP中你可以像这样用一块石头杀死2只鸟:
代替:
if(getData()){
$data = getData();
echo $data;
}
Run Code Online (Sandbox Code Playgroud)
我可以做这个:
if($data = getData()){
echo $data;
}
Run Code Online (Sandbox Code Playgroud)
您检查是否getData()存在,如果存在,则将其分配给一个语句中的变量.
我想知道在Python中是否有办法做到这一点?所以不要这样做:
if request.GET.get('q'):
q = request.GET.get('q')
print q
Run Code Online (Sandbox Code Playgroud)
避免写request.GET.get('q')两次.
Amb*_*ber 25
可能不完全是你在想什么,但......
q = request.GET.get('q')
if q:
print q
Run Code Online (Sandbox Code Playgroud)
这个?
Ale*_*lli 25
在这里看到我8岁的食谱只是为了这个任务.
# 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())
Run Code Online (Sandbox Code Playgroud)
亚历克斯答案的一个变种:
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()
Run Code Online (Sandbox Code Playgroud)
用法:
if save_data(get_input()):
print save_data.value
Run Code Online (Sandbox Code Playgroud)
或者如果您更喜欢替代界面:
if save_data.set(get_input()):
print save_data.get()
Run Code Online (Sandbox Code Playgroud)
我会发现这有助于在if-elif-elif-elif等结构中测试一系列正则表达式,就像在这个SO问题中一样:
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)
Run Code Online (Sandbox Code Playgroud)