0

Python で一連の変数を出力する場合、次のようなかなりの数のオプションがあります。

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

また

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

2 番目の例で print の代わりに sys.stdout.write を使用する理由は、ラムダが print を受け入れないためですが、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 でレイズするためのそのようなオブジェクトはありますか? もしそうなら、それはどこにありますか?

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あなたがしようとしているように、ラムダで使用することはできないと思います。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

関数は他のより複雑な関数の単純化であると思うので、範囲のステップパラメーターがあることを無視します。

于 2010-09-17T03:40:25.030 に答える