[英]In python 2.7, how can I compare lines with the number of items in a list?
我嘗試打印第[4]行(如果有4個項目),或者打印第[4]和[5]行(如果有4個以上)。
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和just
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的內置函數文檔
您可以使用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]
假設您始終至少有四個項目!
if len(lines)> 4
則應使用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.