python - 寻找更多的pythonic方法

标签 python

刚刚写了这个函数...

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

但是感觉 pythonic 还不够,有什么建议吗?

最佳答案

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)

关于python - 寻找更多的pythonic方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11357655/

相关文章:

python - 在具有条件的 DataFrame.index 中查找最小值

python - 使用格式和变量将字符串居中

python - 无法从 OpenCV Gstreamer 接收 gstreamer UDP 流

python - Numpy 花哨的索引是否将值直接复制到另一个数组?

python - 如何在scrapy中使用项目字段对xml进行排序?

python - 如何在python中用颜色代码绘制矩阵稀疏模式?

python - 如何将我的 Python 3 应用程序编译为 .exe?

Python 为 Blur.io 签署 EIP-712 消息

python - 如何使用嵌套字典中的子列创建数据框(多索引)?

python - 试图找出最长路径算法python