在python 2.7中,如何将行与列表中的项目数进行比较



如果有 4 个项目,我正在尝试打印行 [4],如果有超过 4 个项目,我正在尝试打印行 [4] 和 [5]。

def onlinedoc(test):
    for line in test:
        lines = line.split()
        if 'report' in lines:
            if lines > [4]:      #<---- this is where i need help
                doc = lines[4] + lines[5]
            else:
                doc = lines[4]
    return doc
if __name__ == '__main__':
    test = open('test_documentation.txt', 'r')
    print
    onlinedoc(test)

我不确定如果行> [4] ,我应该把什么放在我有的地方。我总是得到IndexError: list index out of range.我已经仔细检查了,我想要的信息将在 [4] 或 [5] 中。如果我将这些行复制到单独的文本中并在没有 if else 的情况下执行此操作,而只是

if 'report' in lines:
    host = lines[4] + lines[5]

然后它工作(在带有 5 的行上)。

使用 len

def onlinedoc(test):
    for line in test:
        lines = line.split()
        if 'report' in lines:
            if len(lines) > 4:
                doc = lines[4] + lines[5]
            else:
                doc = lines[4]
    return doc

你应该阅读Python的内置函数文档

你应该使用if len(lines)> 4

您可以使用 len(lines) 或 try/except

if 'report' in lines:
    if len(lines) > 4:
        doc = lines[4] + lines[5]
    else:
        doc = lines[4]

或尝试/除非

if 'report' in lines:
    try:
        doc = lines[4] + lines[5]
    except IndexError:
        doc = lines[4]

这假设您始终至少有四个项目!

最新更新