相关疑难解决方法(0)

简短(有用)的python片段

本着"你最有用的C/C++代码片段"的精神- 线程:

你们有没有(通常)使用的简短的单功能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 …
Run Code Online (Sandbox Code Playgroud)

python code-snippets

46
推荐指数
12
解决办法
3万
查看次数

如何在python中创建嵌套列表?

我知道你可以在python中创建容易嵌套的列表,如下所示:

[[1,2],[3,4]]
Run Code Online (Sandbox Code Playgroud)

但是如何创建一个3x3x3的零矩阵?

[[[0] * 3 for i in range(0, 3)] for j in range (0,3)]
Run Code Online (Sandbox Code Playgroud)

要么

[[[0]*3]*3]*3
Run Code Online (Sandbox Code Playgroud)

似乎不对.没有办法创建它只是将维度列表传递给方法?例如:

CreateArray([3,3,3])
Run Code Online (Sandbox Code Playgroud)

python arrays list matrix nested-lists

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

python ×2

arrays ×1

code-snippets ×1

list ×1

matrix ×1

nested-lists ×1