当前位置:优学网  >  在线题库

如何重用循环过滤文件名的结果,而不是每次都再次过滤?

发表时间:2022-07-24 01:30:57 阅读:187

该脚本为VS代码扩展名"Notes"(Dion Munk)用户生成一个目录.md文件,并按预期工作.

然而,get_body()效率极低,因为它会重新扫描所有文件,查找`cats(categories)字典中的每个键.

我怎样才能只在文件中循环一次,仍然达到预期的结果?

_总有机碳含量

"""
Python script to generate a table of contents .md file for VSCode "Notes" users
Run script in Notes.notesLocation to generate, then open _toc.md in preview mode
User must prefix note file names with corresponding values in cats (categories)
    i.e. dj_admin_model.md, py_polymorphism.md, st_ascii.md 
User could put a top link in every note to quickly return to table of contents
    e.g. [< content](_toc.md)
"""
import os

dbug = True
path = '.'
ftyp = '.md'
file = '_toc.md'
cats = {
   'Config'    : '_',
   'Django'    : 'dj_',
   'Markdown'  : 'md_',
   'Python'    : 'py_',
   'Standard'  : 'st_',
   'VSCode'    : 'vs_',
}

def get_files():
    for _, _, files in os.walk(path):
        return (f for f in files if f.lower().endswith(ftyp.lower()))

def get_body():
   body = \
      f'["{file}" generated by running "{__file__}".]: #\n\n# 所容纳之物\n\n'

   for key, val in cats.items():
      body += f'### {key}\n'
      # relooping files for each key in cats inefficient - TODO
      for f in get_files():
         if f.startswith(val):
            body += \
               f"- [{f.replace('.md', '').split('_', 1)[1]}]({f})\n"
      body += '\n'
   return body

def write_toc():
   with open(file, mode='wt') as f:
      f.write(get_body())

def print_toc():
   with open(file) as f:
      print(f.read())

def main():
   write_toc()
   if dbug:
      print('_'*60)
      print_toc()

if __name__ == '__main__':
   main()

_toc.md(期望输出示例)

["_toc.md" generated by running "_总有机碳含量".]: #

# 所容纳之物

### Config
- [toc](_toc.md)

###Django公司
- [admin_model](dj_admin_model.md)

###降价
- [syntax](md_syntax.md)

###Python
- [file_stream](py_file_stream.md)
- [operators](py_operators.md)
- [pip](py_pip.md)
- [polymorphism](py_polymorphism.md)
- [venv](py_venv.md)

###标准
- [ascii](st_ascii.md)

###VSCode代码
- [keyboard](vs_keyboard.md)

_toc.md(模拟预览)

所容纳之物

Django公司

-管理员模型

降价

-语法

Python

-运营商 -pip -多态性 -venv

标准

-ascii

VSCode代码

-键盘

🎖️ 优质答案
  • f_list solution by Jarvis - get_files() now only called once!

    Revised get_body():

    def get_body():
       f_list = list(get_files())
       body = \
          f'["{file}" generated by running "{__file__}".]: #\n\n# Content\n\n'
    
       for key, val in cats.items():
          body += f'### {key}\n'
          for f in f_list:
             if f.startswith(val):
                body += \
                   f"- [{f.replace('.md', '').split('_', 1)[1]}]({f})\n"
          body += '\n'
       return body
  • 相关问题