2012-06-22 45 views
-1

我想打印行[4]如果有4项,或行[4]和[5]如果有超过4项。在Python 2.7中,如何将行与列表中的项目数进行比较?

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 'report' in lines: 
    host = lines[4] + lines[5] 

那么它的工作原理(上线与5)。

+0

这是很清楚你想要做什么。我们不知道你的意思是“4线” – Falmarri

+0

一行4项或一行5项拆分 – Mike

+1

它不是很不清楚。问题是你正试图执行一个语法不正确的命令。看看len()函数,并重新评估if-expression中的条件,从而带来问题 –

回答

1

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

1

您可以使用LEN(系)或尝试/除

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] 

这里假设你总是至少有四个项目!

2

使用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的documentation的内置函数

相关问题