繁体   English   中英

Python for循环使用范围导致打印索引而不是值

[英]Python for loop using range results in the index being printed rather than the value

我正在循环比较两个配置文件的difflib的以下输出:-

[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]

我要实现的是解析diff并仅打印出列表中下一项以+开头的标头([]中的项目)

我有下面的代码运行没有错误。

for x in range(0, (len(diff) - 1)):
        print str(x)  #prints index number instead of the content of the line
        z = str(diff)[x+1]
        if str(x).startswith('+'):
            print(x) # prints nothing x contains the index of the line instead of the text
        elif str(x).startswith('  [') and z.startswith('+'):
            print(x)

问题在于该行的索引号是在循环中返回的,而不是该行中的文本。

例如打印输出

[0]
[1]
[2]
[3]
[4]

我知道我一定在这里缺少一些基本的知识,但之后似乎找不到答案。

您正在执行的操作是使范围为0的x循环到diff-1的长度。这将为您提供这两个整数之间的所有整数值,例如

    for x in range(0, 3):
        print(str(x) + ' ')

会给你:

0 1 2 3

因此,如果diff是每个新行的字符串列表,要获取该行,您可以使用:

    # iterate through list diff
    for x in diff:
        print(x)

打印出所有行。 如果现在想在打印出来之前先了解其标题:

    # iterate through list diff
    for x in diff:
        # test if x is a header
        if x.startswith('[') and x.endswith(']'):
            print(x)

请注意,此代码均未经过测试。

希望这可以帮助

编辑:如果diff不是行列表而是一个字符串,则可以使用

    line_list = diff.split('\n')

获得行列表。

编辑2:如果您现在还想在第一次迭代中检查下一行,我们必须改用索引:

    # for every index in list diff
    for i in range(0, len(diff) - 1):
        if diff[i].startswith('[') and diff[i + 1].startswith('+'):
            # do something if its a header with following content
        elif diff[i].startswith('+'):
            # do something if the line is data
for x in range(0, (len(diff) - 1)):
    print str(x)  #prints index number instead of the content of the line

在这里打印索引的原因是因为x不在diff的内容上进行迭代,而是在等于diff的长度的整数范围内进行迭代。 您已经有了答案,为什么打印在接下来的一行中给出了索引而不是字符串内容: z = str(diff)[x+1]调用diff[x]是指diff所在的行索引x,因此,如果要打印diff的内容或在以后的行中引用它,则需要执行相同的操作: print str(diff[x])

感谢上面的@pheonix和@rdowell评论。 我已经将代码更新为以下代码,现在可以正常工作:-

for i in range(0, len(diff) - 1):
    if diff[i].startswith('  [') and diff[i + 1].startswith('+'):
            # do something if its a header with following content
        print str(diff[i])
    elif diff[i].startswith('+'):
            # do something if the line is data
        print str(diff[i])

我将再次引用这篇文章,因为我只是要了解Python中不同对象类型可以做什么和不能做什么

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM