是否有像 Ruby 的 andand 这样的 Python 库(或模式)? [英] Is there a Python library (or pattern) like Ruby's andand?

查看:65
本文介绍了是否有像 Ruby 的 andand 这样的 Python 库(或模式)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个对象 x,它可能是 None 或浮点数的字符串表示.我想做以下事情:

For example, I have an object x that might be None or a string representation of a float. I want to do the following:

do_stuff_with(float(x) if x else None)

除了不必键入 x 两次,就像 Ruby 的 and 库一样:

Except without having to type x twice, as with Ruby's andand library:

require 'andand'
do_stuff_with(x.andand.to_f)

推荐答案

我们没有其中之一,但不难推出您自己的方案:

We don't have one of those but it isn't hard to roll your own:

def andand(x, func):
    return func(x) if x else None

>>> x = '10.25'
>>> andand(x, float)
10.25
>>> x = None
>>> andand(x, float) is None
True

这篇关于是否有像 Ruby 的 andand 这样的 Python 库(或模式)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆