作为 iPython 新手,我们可能想知道是否有办法获取最后一个赋值变量的值。就像在 R 语言中可以使用 .Last.value
获取最后赋值变量的值一样。
2、解决方案
方法一:使用 _
快捷键
有一个快捷键可以获取最后返回的对象,即 _
。
In [1]: 1 + 3
Out[1]: 4
In [2]: _
Out[2]: 4
方法二:使用 %last
魔术方法
我们可以使用 IPython 中的 In
和 Out
变量,它们分别包含输入的命令/语句和这些语句的相应输出(如果有)。因此,一种简单的方法是使用这些变量作为定义 %last
魔术方法的基础。但是,由于并非所有语句都会生成输出,In
和 Out
是不同步的。因此,我们采用了一种方法是解析 In
,查找 =
的出现,并解析那些行的输出:
def last_assignment_value(self, parameter_s=''):
ops = set('()')
has_assign = [i for i,inpt in enumerate(In) if '=' in inpt] #find all line indices that have `=`
has_assign.sort(reverse=True) #reverse sort, because the most recent assign will be at the end
for idx in has_assign:
inpt_line_tokens = [token for token in In[idx].split(' ') if token.strip() != ''] #
indices = [inpt_line_tokens.index(token) for token in inpt_line_tokens if '=' in token and not any((c in ops) for c in token)]
#Since assignment is an operator that occurs in the middle of two terms
#a valid assignment occurs at index 1 (the 2nd term)
if 1 in indices:
return ' '.join(inpt_line_tokens[2:]) #this simply returns on the first match with the above criteria
And, lastly to make that your own custom command in IPython:
get_ipython().define_magic('last', last_assignment_value)
现在,我们可以调用 %last
魔术方法来获取最后一个赋值变量的值:
%last
但是,请注意,此方法以字符串形式输出赋值的术语,它可能与您想要的不同。
方法三:使用 parser
模块评估表达式
我们可以使用 parser
模块来尝试评估表达式,并将此功能添加到 last_assignment_value
函数中。但是,由于 eval
函数的潜在危险,我们最好只在验证了输入的有效性后才使用它。
import parser
def eval_expression(src):
try:
st = parser.expr(src)
code = st.compile('obj.py')
return eval(code)
except SyntaxError:
print 'Warning: there is a Syntax Error with the RHS of the last assignment! "%s"' % src
return None
现在,我们可以通过扩展 last_assignment_value
函数来使用此功能:
def last_assignment_value(self, parameter_s=''):
ops = set('()')
has_assign = [i for i,inpt in enumerate(In) if '=' in inpt] #find all line indices that have `=`
has_assign.sort(reverse=True) #reverse sort, because the most recent assign will be at the end
for idx in has_assign:
inpt_line_tokens = [token for token in In[idx].split(' ') if token.strip() != ''] #
indices = [inpt_line_tokens.index(token) for token in inpt_line_tokens if '=' in token and not any((c in ops) for c in token)]
#Since assignment is an operator that occurs in the middle of two terms
#a valid assignment occurs at index 1 (the 2nd term)
if 1 in indices:
result = ' '.join(inpt_line_tokens[2:]) #this simply returns on the first match with the above criteria
return eval_expression(result)
And, lastly to make that your own custom command in IPython:
get_ipython().define_magic('last', last_assignment_value)