简体   繁体   English

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

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

I'm looping over the below output from a difflib compare of two configuration files:- 我正在循环比较两个配置文件的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]

what I'm trying to achieve is to parse the diff and only print out headers (items in []) for which the next item in the list starts with + 我要实现的是解析diff并仅打印出列表中下一项以+开头的标头([]中的项目)

I have the following code that is running without errors. 我有下面的代码运行没有错误。

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)

The problem is that the index number of the line is being returned in the loop rather than the text in the line. 问题在于该行的索引号是在循环中返回的,而不是该行中的文本。

eg print output from 例如打印输出

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

I know I must be missing something basic here but can't seem to find the answer after. 我知道我一定在这里缺少一些基本的知识,但之后似乎找不到答案。

What you are doing is looping through an x of the range 0 to length of diff - 1. This will provide you with all integer values between those two integers, eg 您正在执行的操作是使范围为0的x循环到diff-1的长度。这将为您提供这两个整数之间的所有整数值,例如

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

will give you back: 会给你:

0 1 2 3

So if diff is a list of strings for each new line, to get the line, you can just use : 因此,如果diff是每个新行的字符串列表,要获取该行,您可以使用:

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

to print out all of your lines. 打印出所有行。 If you now want to know if its a header before you print it out: 如果现在想在打印出来之前先了解其标题:

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

Please note that none of this code has been tested. 请注意,此代码均未经过测试。

Hope this helps 希望这可以帮助

EDIT: if diff is not a list of lines but rather one single string, you can use 编辑:如果diff不是行列表而是一个字符串,则可以使用

    line_list = diff.split('\n')

to get a list of lines. 获得行列表。

EDIT 2: If you now want to also check the next line within the first iteration, we have to use indexes instead: 编辑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

The reason the index is being printed here is because x is not iterating over the contents of diff, it's iterating over an integer range that is equal to the length of diff. 在这里打印索引的原因是因为x不在diff的内容上进行迭代,而是在等于diff的长度的整数范围内进行迭代。 You already have the answer as to why your print is giving the index instead of the string content here, on the very next line: z = str(diff)[x+1] Calling diff[x] refers to the line of diff at index x, so if you want to print diff's content or refer to it in later lines you need to do the same thing: print str(diff[x]) 您已经有了答案,为什么打印在接下来的一行中给出了索引而不是字符串内容: z = str(diff)[x+1]调用diff[x]是指diff所在的行索引x,因此,如果要打印diff的内容或在以后的行中引用它,则需要执行相同的操作: print str(diff[x])

thanks to both @pheonix and @rdowell comments above. 感谢上面的@pheonix和@rdowell评论。 I've updated the code to the below which now works:- 我已经将代码更新为以下代码,现在可以正常工作:-

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

This post will be something I'll refer back to as I'm just getting to know what you can and can't do with the different object types in Python 我将再次引用这篇文章,因为我只是要了解Python中不同对象类型可以做什么和不能做什么

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

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