在for循环中的条件内使用列表中的下一项

时间:2018-03-07 11:46:10

标签: python list if-statement

我有以下循环,它解析了2个配置文件的difflib比较的输出,到目前为止显示了文件2(用+表示)和文件中的标题的差异 差异属于例如[服务器]

#!/usr/bin/env python

import difflib
from difflib import Differ

conf = open('C:/Users/fitzs/Documents/Scripts/example_ISAM_conf_file.txt', 'r')
upconf = open('C:/Users/fitzs/Documents/Scripts/Updated_ISAM_conf_file.txt', 'r')

d = difflib.Differ()

diff = list(d.compare(conf.readlines(), upconf.readlines()))# creates a 'generator' list of diffs

delta = ''.join(diff).strip('# ') #converts the list to string


for x in diff:
    x = str(x).strip()
    if x.startswith('+'):
        print(x)
    elif x.startswith('['):
        print(x)

示例输出: -

    The above code is giving me the following example output so far.  

    [server]
    + # web-host-name = www.myhost.com
    + https-port = 1080
    + network-interface = 0.0.0.0
    [process-root-filter]
    [validate-headers]
    [interfaces]
    [header-names]
    [oauth]
    [tfim-cluster:oauth-cluster]
    [session]
    + preserve-inactivity-timeout = 330
    [session-http-headers]

我想要做的只是打印一个标题(例如[server])如果列表中的下一个元素以+开头,从而排除了它们下面没有任何增量的标题'

换句话说,必须满足标题打印2条件的行: 1.该行必须以[以[ 2.下一行必须以+

开头

例如:

[server]
+ # web-host-name = www.myhost.com
+ https-port = 1080
+ network-interface = 0.0.0.0
[session]
+ preserve-inactivity-timeout = 330

为实现这一点,我尝试将上面的for循环更改为以下内容:

for x in range(0, len(diff)):
    stanza = diff[x+1]
    x = str(x).strip()
    if x.startswith('+'):
        print(x)
    elif x.startswith('[') and stanza.startswith('+'):
        print(x)

但是,这会导致以下错误:

Traceback (most recent call last):
  File "C:/Users/fitzs/PycharmProjects/Pydiffer/Pydiffer.py", line 35, in <module>
    stanza = diff[x+1]
IndexError: list index out of range

感谢以下建议,我已按如下方式更新了我的代码,现在它运行时没有错误。但是索引似乎是在循环中返回而不是实际的行本身: -

我的for循环现在看起来像: -

for x in range(0, (len(diff) - 1)):
    # print (diff)
    y = str(x)
    print (x) 
    z = diff[x+1]
    if y.startswith('+'):
        print(y)
    elif y.startswith('[') and z.startswith('+'): 
        print(y)

2 个答案:

答案 0 :(得分:0)

错误的主要原因是x+1超出索引,因为(len(diff) +1)等于range(len(diff)-1)。请使用range(0,len(diff)-1)app.js

答案 1 :(得分:0)

我没有浏览你的脚本,但可以通过将for循环更改为以下

来解决错误
for x in range(0, (len(diff)-1):

您收到该错误,因为在stanze=diff[x+1]中您要求的元素是len(diff)+1,这是不存在的。