相关疑难解决方法(0)

了解切片表示法

我需要在Python的切片表示法上有一个很好的解释(引用是一个加号).

对我来说,这种符号需要一点点提升.

它看起来非常强大,但我还没有完全了解它.

python iterable list slice

3024
推荐指数
33
解决办法
159万
查看次数

使用Python获取文件的最后n行,类似于tail

我正在为Web应用程序编写一个日志文件查看器,为此我想通过日志文件的行分页.文件中的项目是基于行的,底部是最新项目.

所以我需要一种tail()方法,可以n从底部读取行并支持偏移量.我想出的是这样的:

def tail(f, n, offset=0):
    """Reads a n lines from f with an offset of offset lines."""
    avg_line_length = 74
    to_read = n + offset
    while 1:
        try:
            f.seek(-(avg_line_length * to_read), 2)
        except IOError:
            # woops.  apparently file is smaller than what we want
            # to step back, go to the beginning instead
            f.seek(0)
        pos = f.tell()
        lines = f.read().splitlines()
        if len(lines) >= to_read or pos == 0:
            return lines[-to_read:offset and -offset or None]
        avg_line_length …
Run Code Online (Sandbox Code Playgroud)

python file-io file tail logfiles

174
推荐指数
10
解决办法
14万
查看次数

"'生成器'对象不可订阅"错误

在尝试解决Project Euler Problem 11时,为什么我从代码的第5行收到此错误?

for x in matrix:
    p = 0
    for y in x:
        if p < 17:
            currentProduct = int(y) * int(x[p + 1]) * int(x[p + 2]) * int(x[p + 3])
            if currentProduct > highestProduct:
                print(currentProduct)
                highestProduct = currentProduct
        else:
                break
            p += 1
Run Code Online (Sandbox Code Playgroud)
'generator' object is not subscriptable
Run Code Online (Sandbox Code Playgroud)

python generator

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

标签 统计

python ×3

file ×1

file-io ×1

generator ×1

iterable ×1

list ×1

logfiles ×1

slice ×1

tail ×1