简短(有用)的python片段

2024-06-16 10:13:07 发布

您现在位置:Python中文网/ 问答频道 /正文

本着现有"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)

Tags: pathinpyforoscountprintsignore
3条回答

我知道的唯一一个真正让我吃惊的“窍门”是列举。它允许您访问for循环中元素的索引。

>>> l = ['a','b','c','d','e','f']
>>> for (index,value) in enumerate(l):
...     print index, value
... 
0 a
1 b
2 c
3 d
4 e
5 f

我喜欢使用any和生成器:

if any(pred(x.item) for x in sequence):
    ...

而不是像这样写的代码:

found = False
for x in sequence:
    if pred(x.n):
        found = True
if found:
    ...

我最初是从彼得·诺维格那里学到这项技术的。

初始化二维列表

虽然这可以安全地初始化列表:

lst = [0] * 3

对于二维列表(列表列表),同样的技巧不起作用:

>>> lst_2d = [[0] * 3] * 3
>>> lst_2d
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> lst_2d[0][0] = 5
>>> lst_2d
[[5, 0, 0], [5, 0, 0], [5, 0, 0]]

运算符*复制其操作数,用[]构造的重复列表指向同一列表。正确的方法是:

>>> lst_2d = [[0] * 3 for i in xrange(3)]
>>> lst_2d
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> lst_2d[0][0] = 5
>>> lst_2d
[[5, 0, 0], [0, 0, 0], [0, 0, 0]]

相关问题 更多 >