【问题标题】:How can I get the line of index + 1 when enumerating lines in Python在Python中枚举行时如何获得索引+ 1的行
【发布时间】:2021-11-29 17:30:32
【问题描述】:

我正在使用代码for index, line in enumerate(lines): 阅读文件的行。我可以使用 (line) 访问当前行的字符串。

是否可以访问下一行以向前看?我尝试使用next_line = line(index + 1) 访问它,但这会产生错误。

代码

with open(sys.argv[1]) as f1:
    with open(sys.argv[2], 'a') as f2:
        lines = f1.readlines()
        prev_line = ""
        string_length = 60
        for index, line in enumerate(lines):
            next_line = line(index + 1)
            print(f'Index is {index + 1}')
            # Do something here

【问题讨论】:

  • 您的实际目标是真的“索引”文件,还是只是成对地迭代行?
  • 这能回答你的问题吗? Iterate a list as pair (current, next) in Python
  • 您好宫城先生,谢谢您的回答。我的目标是查看下一行是否以连字符开头,如果是,则打印当前行,因此下一行(以连字符开头)将以连字符开头。这有意义吗?
  • 你在问如何索引一个列表??

标签: python python-3.x enumerate


【解决方案1】:

line 是一个字符串,因此你不能做你需要的。 试试这样的:

with open(sys.argv[1]) as f1:
    with open(sys.argv[2], 'a') as f2:
        lines = f1.readlines()
        prev_line = ""
        string_length = 60
        for index, line in enumerate(lines):
            try:
                next_line = lines[index + 1]
            except IndexError:
                pass
            print(f'Index is {index + 1}')
            # Do something here

【讨论】:

  • IMO,必须使用 try/except 来避免一个错误
【解决方案2】:

您可以像往常一样从列表中访问它,这会在最后一次迭代中导致异常,所以我添加了一个检查来防止这种情况:

with open(sys.argv[1]) as f1:
    with open(sys.argv[2], 'a') as f2:
        lines = f1.readlines()
        prev_line = ""
        string_length = 60
        for index, line in enumerate(lines):
            if index < len(lines) - 1:
                next_line = lines[index+1]
                print(f'Index is {index + 1}')
                # Do something here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    相关资源
    最近更新 更多