リストの内包表記で 'else' を使用することは可能ですか? [重複] 質問する

リストの内包表記で 'else' を使用することは可能ですか? [重複] 質問する

リスト内包表記に変換しようとしたコードは次のとおりです。

table = ''
for index in xrange(256):
    if index in ords_to_keep:
        table += chr(index)
    else:
        table += replace_with

この理解に else ステートメントを追加する方法はありますか?

table = ''.join(chr(index) for index in xrange(15) if index in ords_to_keep)

ベストアンサー1

構文はa if b else cPython の三項演算子であり、a条件がb真の場合は に評価され、そうでない場合は に評価されますc。これは、理解ステートメントで使用できます。

>>> [a if a else 2 for a in [0,1,0,3]]
[2, 1, 2, 3]

あなたの例では、

table = ''.join(chr(index) if index in ords_to_keep else replace_with
                for index in xrange(15))

おすすめ記事