在Python2.7中,如何将行与列表中的项数进行比较?
如果有4项,我尝试打印第[4]行;如果有4项以上,我尝试打印第[4]行和第[5]行在Python2.7中,如何将行与列表中的项数进行比较?,python,loops,if-statement,python-2.7,Python,Loops,If Statement,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] + l
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)
然后它就可以工作了(在有5个字符的行上)。您可以使用len(行)或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]
或尝试/除外
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]
这假设您始终至少有四项 使用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的内置函数如果len(lines)>4,您应该使用
您很不清楚要做什么。我们不知道你所说的“一行四项”是什么意思一行四项还是一行五项,如果不是很清楚的话。问题是您试图执行语法错误的命令。查看len()函数,并重新计算if表达式中出现问题的条件