寻找更多的pythonic方法

时间:2012-07-06 07:24:51

标签: python

刚刚写了这个函数......

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

然而,感觉不到pythonic'够',建议?

4 个答案:

答案 0 :(得分: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)

答案 1 :(得分:5)

您可以删除匹配的前导字符,并根据长度计算差异。

def nrofleadingchars(stringtotest, testchar='\t'):
    return (len(stringtotest) - len(stringtotest.lstrip(testchar))

答案 2 :(得分:2)

在我看来,代码很简单,所以你应该更喜欢一些难以理解的混乱。 我会稍微缩短一点:

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

答案 3 :(得分: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

这些是时间比率。向下的第一列可以读作“慢一点”。