alex321
V2EX  ›  问与答

求教一个 Python 在 for 循环中超出范围的古怪问题

  •  
  •   alex321 · Sep 24, 2019 · 1638 views
    This topic created in 2434 days ago, the information mentioned may be changed or developed.

    操作

    我有一个文本文件,1090 行,通过 readlines 读取到一个 list 中。

    代码

    with open(file_path, 'rb') as f:
        lines  = f.readlines()
    
    print(len(lines), lines[1089])
    
    i = 0
    for _ in lines:
        i += 1
    print(i)
    
    i = 0
    for line in lines:
        i += 1
    print(i)
    

    问题

    第一个 print 正常输出,这个没问题;第二个直接遍历 lines 计数,得到的是 1090,也没问题。

    但是,第三个遍历 lines 计数,就得到的是 1055。很古怪,请大佬们指教。

    2 replies    2019-09-25 01:18:20 +08:00
    junnplus
        1
    junnplus  
       Sep 25, 2019 via iPhone
    你确定代码是完整的么
    Trim21
        2
    Trim21  
       Sep 25, 2019
    你中间修改过 lines 这个变量吧
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5300 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 67ms · UTC 01:17 · PVG 09:17 · LAX 18:17 · JFK 21:17
    ♥ Do have faith in what you're doing.