3

この関数を書いたばかりです...

def nrofleadingchars(stringtotest, testchar='\t'):
    count = 0
    for c in stringtotest:
        if c == testchar:
            count = count + 1
        else:
            return count
    return count

しかし、pythonic'十分'、提案を感じませんか?

4

4 に答える 4

9
import itertools

def nrofleadingchars(stringtotest, testchar='\t'):
    return len(list(itertools.takewhile(lambda x: x == testchar, stringtotest)))

リストを作成する必要があるため、プレフィックスが非常に大きいものでは効率が低下する可能性があります。もし私がそのようなことを潜在的に扱うつもりなら、私はおそらく代わりにこれを書くでしょう:

def num_leading_chars(a_string, prefix='\t'):
    for idx, char in enumerate(a_string):
        if char != prefix:
            return idx
    return len(a_string)
于 2012-07-06T07:26:50.877 に答える
5

一致する先頭の文字を削除し、長さに基づいて差を計算できます。

def nrofleadingchars(stringtotest, testchar='\t'):
    return (len(stringtotest) - len(stringtotest.lstrip(testchar))
于 2012-07-06T07:27:42.440 に答える
2

私の意見では、コードは単純なので、読めない混乱よりもそれを好むべきです。少し短くします。

def nrofleadingchars(stringtotest, testchar='\t'):
    count = 0
    for c in stringtotest:
        if c != testchar:
            break
        count += 1
    return count
于 2012-07-06T07:32:07.827 に答える
1

これは答えではありませんが、この情報をここに置く方法がわかりません。

パフォーマンスも考慮事項である場合(それは常に私にとってです)、ここに現在の回答のレポートがあります。

                          nrofleadingchars_orig | nrofleadingchars_1 | nrofleadingchars_it | num_leading_chars | nrofleadingchars_len
-------------------------------------------------- -------------------------------------------------- ------------------------------
nrofleadingchars_ori:1.0 | 1.05393899527 | 0.603740407137 | 1.2923361749 | 23.1678811895
  nrofleadingchars_1:0.948821520491 | 1.0 | 0.572841891082 | 1.22619637446 | 21.9821842568
 nrofleadingchars_it:1.65634101706 | 1.74568238735 | 1.0 | 2.14054941432 | 38.3739118926
   num_leading_chars:0.773792469344 | 0.815530057691 | 0.467169780482 | 1.0 | 17.9271319951
nrofleadingchars_len:0.0431632047756 | 0.045491384674 | 0.0260593708246 | 0.0557813709562 | 1.0

これらはタイミング比です。下の最初の列は「倍遅い」と読むことができます。

于 2012-07-06T08:02:53.420 に答える