pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

遍歷字符串的行

Iterate over the lines of a string(遍歷字符串的行)
本文介紹了遍歷字符串的行的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!

問題描述

我有一個這樣定義的多行字符串:

I have a multi-line string defined like this:

foo = """
this is 
a multi-line string.
"""

我們將這個字符串用作我正在編寫的解析器的測試輸入.解析器函數(shù)接收一個 file 對象作為輸入并對其進行迭代.它還直接調(diào)用 next() 方法來跳過行,所以我真的需要一個迭代器作為輸入,而不是一個可迭代的.我需要一個迭代器來迭代該字符串的各個行,就像 file-object 將遍歷文本文件的行一樣.我當(dāng)然可以這樣做:

This string we used as test-input for a parser I am writing. The parser-function receives a file-object as input and iterates over it. It does also call the next() method directly to skip lines, so I really need an iterator as input, not an iterable. I need an iterator that iterates over the individual lines of that string like a file-object would over the lines of a text-file. I could of course do it like this:

lineiterator = iter(foo.splitlines())

有沒有更直接的方法?在這種情況下,字符串必須遍歷一次以進行拆分,然后再由解析器遍歷.在我的測試用例中沒關(guān)系,因為那里的字符串很短,我只是出于好奇而問.Python 為這些東西提供了很多有用且高效的內(nèi)置函數(shù),但我找不到適合這種需要的東西.

Is there a more direct way of doing this? In this scenario the string has to traversed once for the splitting, and then again by the parser. It doesn't matter in my test-case, since the string is very short there, I am just asking out of curiosity. Python has so many useful and efficient built-ins for such stuff, but I could find nothing that suits this need.

推薦答案

這里有三種可能:

foo = """
this is 
a multi-line string.
"""

def f1(foo=foo): return iter(foo.splitlines())

def f2(foo=foo):
    retval = ''
    for char in foo:
        retval += char if not char == '
' else ''
        if char == '
':
            yield retval
            retval = ''
    if retval:
        yield retval

def f3(foo=foo):
    prevnl = -1
    while True:
      nextnl = foo.find('
', prevnl + 1)
      if nextnl < 0: break
      yield foo[prevnl + 1:nextnl]
      prevnl = nextnl

if __name__ == '__main__':
  for f in f1, f2, f3:
    print list(f())

將其作為主腳本運行可確認這三個功能是等效的.使用 timeit (以及 * 100 用于 foo 以獲得大量字符串以進行更精確的測量):

Running this as the main script confirms the three functions are equivalent. With timeit (and a * 100 for foo to get substantial strings for more precise measurement):

$ python -mtimeit -s'import asp' 'list(asp.f3())'
1000 loops, best of 3: 370 usec per loop
$ python -mtimeit -s'import asp' 'list(asp.f2())'
1000 loops, best of 3: 1.36 msec per loop
$ python -mtimeit -s'import asp' 'list(asp.f1())'
10000 loops, best of 3: 61.5 usec per loop

請注意,我們需要調(diào)用 list() 來確保遍歷迭代器,而不僅僅是構(gòu)建迭代器.

Note we need the list() call to ensure the iterators are traversed, not just built.

IOW,天真的實現(xiàn)快得多,甚至都不好笑:比我嘗試使用 find 調(diào)用的速度快 6 倍,而后者又比較低級別的方法快 4 倍.

IOW, the naive implementation is so much faster it isn't even funny: 6 times faster than my attempt with find calls, which in turn is 4 times faster than a lower-level approach.

要記住的教訓(xùn):測量總是一件好事(但必須準(zhǔn)確);像 splitlines 這樣的字符串方法以非常快的方式實現(xiàn);通過在非常低的級別編程(尤其是通過非常小片段的 += 循環(huán))將字符串放在一起可能會很慢.

Lessons to retain: measurement is always a good thing (but must be accurate); string methods like splitlines are implemented in very fast ways; putting strings together by programming at a very low level (esp. by loops of += of very small pieces) can be quite slow.

編輯:添加了@Jacob 的建議,稍作修改以提供與其他建議相同的結(jié)果(保留一行尾隨空格),即:

Edit: added @Jacob's proposal, slightly modified to give the same results as the others (trailing blanks on a line are kept), i.e.:

from cStringIO import StringIO

def f4(foo=foo):
    stri = StringIO(foo)
    while True:
        nl = stri.readline()
        if nl != '':
            yield nl.strip('
')
        else:
            raise StopIteration

測量給出:

$ python -mtimeit -s'import asp' 'list(asp.f4())'
1000 loops, best of 3: 406 usec per loop

不如基于 .find 的方法好——仍然值得牢記,因為它可能不太容易出現(xiàn)小錯誤(任何你看到出現(xiàn)+1 和 -1,就像我上面的 f3 一樣,應(yīng)該自動觸發(fā)一對一的懷疑——許多缺乏這種調(diào)整的循環(huán)也應(yīng)該有這些調(diào)整——盡管我相信我的代碼是也是正確的,因為我能夠使用其他功能檢查它的輸出').

not quite as good as the .find based approach -- still, worth keeping in mind because it might be less prone to small off-by-one bugs (any loop where you see occurrences of +1 and -1, like my f3 above, should automatically trigger off-by-one suspicions -- and so should many loops which lack such tweaks and should have them -- though I believe my code is also right since I was able to check its output with other functions').

但基于拆分的方法仍然適用.

But the split-based approach still rules.

順便說一句:f4 可能更好的樣式是:

An aside: possibly better style for f4 would be:

from cStringIO import StringIO

def f4(foo=foo):
    stri = StringIO(foo)
    while True:
        nl = stri.readline()
        if nl == '': break
        yield nl.strip('
')

至少,它不那么冗長了.不幸的是,需要去除尾隨 的需要禁止用 return iter(stri) 更清晰、更快速地替換 while 循環(huán)(>iter 部分在現(xiàn)代版本的 Python 中是多余的,我相信從 2.3 或 2.4 開始,但它也是無害的).也許也值得一試:

at least, it's a bit less verbose. The need to strip trailing s unfortunately prohibits the clearer and faster replacement of the while loop with return iter(stri) (the iter part whereof is redundant in modern versions of Python, I believe since 2.3 or 2.4, but it's also innocuous). Maybe worth trying, also:

    return itertools.imap(lambda s: s.strip('
'), stri)

或其變體——但我在這里停下來,因為它幾乎是一個基于 strip 的理論練習(xí),最簡單,最快,一個.

or variations thereof -- but I'm stopping here since it's pretty much a theoretical exercise wrt the strip based, simplest and fastest, one.

這篇關(guān)于遍歷字符串的行的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!

【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!

相關(guān)文檔推薦

How to draw a rectangle around a region of interest in python(如何在python中的感興趣區(qū)域周圍繪制一個矩形)
How can I detect and track people using OpenCV?(如何使用 OpenCV 檢測和跟蹤人員?)
How to apply threshold within multiple rectangular bounding boxes in an image?(如何在圖像的多個矩形邊界框中應(yīng)用閾值?)
How can I download a specific part of Coco Dataset?(如何下載 Coco Dataset 的特定部分?)
Detect image orientation angle based on text direction(根據(jù)文本方向檢測圖像方向角度)
Detect centre and angle of rectangles in an image using Opencv(使用 Opencv 檢測圖像中矩形的中心和角度)
主站蜘蛛池模板: 贴板式电磁阀-不锈钢-气动上展式放料阀-上海弗雷西阀门有限公司 工业机械三维动画制作 环保设备原理三维演示动画 自动化装配产线三维动画制作公司-南京燃动数字 | 找培训机构_找学习课程_励普教育 | PCB设计,PCB抄板,电路板打样,PCBA加工-深圳市宏力捷电子有限公司 | 骨龄仪_骨龄检测仪_儿童骨龄测试仪_品牌生产厂家【品源医疗】 | 电伴热系统施工_仪表电伴热保温箱厂家_沃安电伴热管缆工业技术(济南)有限公司 | 专业广州网站建设,微信小程序开发,一物一码和NFC应用开发、物联网、外贸商城、定制系统和APP开发【致茂网络】 | 台湾Apex减速机_APEX行星减速机_台湾精锐减速机厂家代理【现货】-杭州摩森机电 | 免费网站网址收录网_海企优网站推荐平台 | 抖音短视频运营_企业网站建设_网络推广_全网自媒体营销-东莞市凌天信息科技有限公司 | 福建珂朗雅装饰材料有限公司「官方网站」 | 锂电叉车,电动叉车_厂家-山东博峻智能科技有限公司 | 镀锌角钢_槽钢_扁钢_圆钢_方矩管厂家_镀锌花纹板-海邦钢铁(天津)有限公司 | 2-羟基泽兰内酯-乙酰蒲公英萜醇-甘草查尔酮A-上海纯优生物科技有限公司 | 广州中央空调回收,二手中央空调回收,旧空调回收,制冷设备回收,冷气机组回收公司-广州益夫制冷设备回收公司 | 深圳宣传片制作-企业宣传视频制作-产品视频拍摄-产品动画制作-短视频拍摄制作公司 | 北京中创汇安科贸有限公司| 全自动端子机|刺破式端子压接机|全自动双头沾锡机|全自动插胶壳端子机-东莞市傅氏兄弟机械设备有限公司 | 企业微信营销_企业微信服务商_私域流量运营_艾客SCRM官网 | 首页-浙江橙树网络技术有限公司 石磨面粉机|石磨面粉机械|石磨面粉机组|石磨面粉成套设备-河南成立粮油机械有限公司 | 超声波焊接机_超音波熔接机_超声波塑焊机十大品牌_塑料超声波焊接设备厂家 | 不锈钢反应釜,不锈钢反应釜厂家-价格-威海鑫泰化工机械有限公司 不干胶标签-不干胶贴纸-不干胶标签定制-不干胶标签印刷厂-弗雷曼纸业(苏州)有限公司 | 氧氮氢联合测定仪-联测仪-氧氮氢元素分析仪-江苏品彦光电 | J.S.Bach 圣巴赫_高端背景音乐系统_官网 | SMC-ASCO-CKD气缸-FESTO-MAC电磁阀-上海天筹自动化设备官网 | Eiafans.com_环评爱好者 环评网|环评论坛|环评报告公示网|竣工环保验收公示网|环保验收报告公示网|环保自主验收公示|环评公示网|环保公示网|注册环评工程师|环境影响评价|环评师|规划环评|环评报告|环评考试网|环评论坛 - Powered by Discuz! | 自动部分收集器,进口无油隔膜真空泵,SPME固相微萃取头-上海楚定分析仪器有限公司 | 挤奶设备过滤纸,牛奶过滤纸,挤奶机过滤袋-济南蓝贝尔工贸有限公司 | 校园文化空间设计-数字化|中医文化空间设计-党建|法治廉政主题文化空间施工-山东锐尚文化传播公司 | 台式恒温摇床价格_大容量恒温摇床厂家-上海量壹科学仪器有限公司 | 长沙广告公司|长沙广告制作设计|长沙led灯箱招牌制作找望城湖南锦蓝广告装饰工程有限公司 | DAIKIN电磁阀-意大利ATOS电磁阀-上海乾拓贸易有限公司 | 上海律师咨询_上海法律在线咨询免费_找对口律师上策法网-策法网 广东高华家具-公寓床|学生宿舍双层铁床厂家【质保十年】 | 飞飞影视_热门电影在线观看_影视大全 | 桌上式超净工作台-水平送风超净工作台-上海康路仪器设备有限公司 | 企业微信scrm管理系统_客户关系管理平台_私域流量运营工具_CRM、ERP、OA软件-腾辉网络 | lcd条形屏-液晶长条屏-户外广告屏-条形智能显示屏-深圳市条形智能电子有限公司 | 米顿罗计量泵(科普)——韬铭机械 | 巨野月嫂-家政公司-巨野县红墙安康母婴护理中心 | 加气混凝土砌块设备,轻质砖设备,蒸养砖设备,新型墙体设备-河南省杜甫机械制造有限公司 | 3d可视化建模_三维展示_产品3d互动数字营销_三维动画制作_3D虚拟商城 【商迪3D】三维展示服务商 广东健伦体育发展有限公司-体育工程配套及销售运动器材的体育用品服务商 | 东莞市超赞电子科技有限公司 全系列直插/贴片铝电解电容,电解电容,电容器 |