2

任意の長さのコンテンツを持つタプルのリストを想定します。

quotes = [('Shakespeare', 'Piccard', 'Allen'),
          ("To be, or not to be", "Earl Grey, 60 degrees", "I feel that life is divided into the horrible and the miserable. That's the two categories. The horrible are like, I don't know, terminal cases, you know, and blind people, crippled. I don't know how they get through life. It's amazing to me. And the miserable is everyone else. So you should be thankful that you're miserable, because that's very lucky, to be miserable."),
          ('beer', 'tea', 'vodka')
         ]

デバッグの目的で、リストの内容を出力したいと思います。

print str(quotes)

ただし、タプル値の最初のN文字だけが必要です。3番目の引用符のように長い場合は、内容全体は必要ありません。リストを反復処理してから各タプルを反復処理して最初のN文字をスライスする関数を記述できることは知っていますが、Pythonであるため、より単純で、より短く、より「Pythonic」な方法があると思います。ある?

現在の例のXYソリューションを探しているわけではありません。これは、ポイントを説明するための単なる例です。

4

2 に答える 2

3

これが十分にpythonicであるかどうかはわかりませんが、それでも:

N = 10
map(lambda t: map(lambda s: s[:N], t), quotes)
于 2012-12-06T21:14:02.253 に答える
1

サブクラス化してみPrettyPrinterます。ソースをざっと見てみると、オーバーライドしたいメソッドは次のようですformat(self, object, context, maxlevels, level)

import pprint

class TruncatingPrettyPrinter(pprint.PrettyPrinter):
    def format(self, object, context, maxlevels, level):
        if isinstance(object, basestring):
            object = object[:72]+"..." # shorten strings to under 80 chars

        return pprint.PrettyPrinter.format(self, object, context, maxlevels, level)

TruncatingPrettyPrinter().pprint(quotes)

これは、構造をラップして整列させるためとまったく同じではありません。また、他の構造の結果の文字列表現ではなく、元のオブジェクトグラフの文字列のみを切り捨てますが、基本的な作業(出力が広すぎない)が実行されます。print str(quotes)pprint

于 2012-12-06T21:20:41.103 に答える