如何获取 iPython 中最后一个赋值变量的值?

作为 iPython 新手,我们可能想知道是否有办法获取最后一个赋值变量的值。就像在 R 语言中可以使用 .Last.value 获取最后赋值变量的值一样。

2、解决方案

方法一:使用 _ 快捷键

有一个快捷键可以获取最后返回的对象,即 _

In [1]: 1 + 3
Out[1]: 4

In [2]: _
Out[2]: 4

方法二:使用 %last 魔术方法

我们可以使用 IPython 中的 InOut 变量,它们分别包含输入的命令/语句和这些语句的相应输出(如果有)。因此,一种简单的方法是使用这些变量作为定义 %last 魔术方法的基础。但是,由于并非所有语句都会生成输出,InOut 是不同步的。因此,我们采用了一种方法是解析 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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值