本着现有"what's your most useful C/C++ snippet"-线程的精神:
你们是否有简短的、单功能的Python代码片段(经常使用)并希望与StackOverlow社区共享?请保持小条目(25以下 可能是台词?)每个帖子只举一个例子。
我将从一个小片段开始,我经常使用它来计算python项目中的sloc(源代码行):
# prints recursive count of lines of python source code from current directory
# includes an ignore_list. also prints total sloc
import os
cur_path = os.getcwd()
ignore_set = set(["__init__.py", "count_sourcelines.py"])
loclist = []
for pydir, _, pyfiles in os.walk(cur_path):
for pyfile in pyfiles:
if pyfile.endswith(".py") and pyfile not in ignore_set:
totalpath = os.path.join(pydir, pyfile)
loclist.append( ( len(open(totalpath, "r").read().splitlines()),
totalpath.split(cur_path)[1]) )
for linenumbercount, filename in loclist:
print "%05d lines in %s" % (linenumbercount, filename)
print "\nTotal: %s lines (%s)" %(sum([x[0] for x in loclist]), cur_path)
我知道的唯一一个真正让我吃惊的“窍门”是列举。它允许您访问for循环中元素的索引。
我喜欢使用
any
和生成器:而不是像这样写的代码:
我最初是从彼得·诺维格那里学到这项技术的。
初始化二维列表
虽然这可以安全地初始化列表:
对于二维列表(列表列表),同样的技巧不起作用:
运算符*复制其操作数,用[]构造的重复列表指向同一列表。正确的方法是:
相关问题 更多 >
编程相关推荐