0

当您想在 Python 中打印一堆变量时,您有很多选择,例如:

for i in range(len(iterable)):
    print iterable[i].name

或者

map(lambda i: sys.stdout.write(i.name), iterable)

我在第二个示例中使用 sys.stdout.write 而不是 print 的原因是 lambdas 不接受打印,但 sys.stdout.write 具有相同的目的。

您还可以使用三元运算符有条件地打印:

map(lambda n: None if n % 2 else sys.stdout.write(str(n)), range(1, 100))

因此,如果我可以检查整个序列中是否存在可以保证异常的条件,那将非常方便:

map(lambda o: raise InvalidObjectError, o.name if not o.isValid else o(), iterable)

但这不起作用。在 Python 中是否有这样的 raise 对象,如果有,它在哪里?

4

4 回答 4

4

没有 Python“对象”(内置或在标准库中)raise,您必须自己构建一个(典型的短片段,放在一个人的util.py......!):

def do_raise(exc): raise exc

通常被称为do_raise(InvalidObjectError(o.name)).

于 2010-09-17T02:50:57.097 回答
2

我认为不可能raise像您尝试做的那样在 lambda 中使用。raise是一个语句/表达式,而不是一个对象。正如@Alex Martelli 所说,您可能需要定义一个函数来为您进行检查。现在,可以在同一上下文中本地声明该函数。

至于异常类型,您的问题似乎是针对的:异常类型不是自动定义的。对于简单的异常类型,您要么只需要一条文本消息,要么根本不需要,通常异常类型仅在您的模块/文件范围内定义为:

class InvalidObjectError(Exception): pass
于 2010-09-17T02:54:48.937 回答
1

做。不是。做。这。

这是一个可怕的想法。

map(lambda o: raise InvalidObjectError, o.name if not o.isValid else o(), iterable)

做这个。

class SomeValidatingClass( object ):
    def isValid( self ):
        try: 
            self.validate()
        except InvalidObjectError:
            return False
        return True
    def validate( self ):
        """raises InvalidObjectErorr if there's a problem."""

[ x.validate() for x in iterable ]

没有地图。没有拉姆达。相同的行为。

于 2010-09-17T17:31:24.203 回答
0

对于您的第一个示例,我使用如下形式:

print '\n'.join(obj.name for obj in iterable)

我也会使用:

firstnotvalid = next(obj.name for obj in iterable if not obj.is_valid())

而不是:

>>> import sys
>>> map(lambda n: None if n % 2 else sys.stdout.write(str(n)), range(1, 100))
2468101214161820222426283032343638404244464850525456586062646668707274767880828486889092949698[None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None]

我会做:

>>> print (', '.join(str(number) for number in range(1,100) if not number % 2))
2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98

忽略范围有 step 参数,因为我认为该功能是其他更复杂功能的简化。

于 2010-09-17T03:40:25.030 回答