Python循环缺少结果

2024-05-19 12:05:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在把一个有13000个名字的文件读到一个列表中。你知道吗

然后,我查看列表中每个项目的每个字符,如果有匹配项,我将从13000行列表中删除该行。你知道吗

如果我运行一次,它会删除列表的一半。在第11轮的时候,它似乎把它降到了9%。为什么这个脚本缺少结果?为什么它会接二连三地抓住它们?你知道吗

使用Python3。你知道吗

with open(fname) as f:
    lines = f.read().splitlines()

bad_letters = ['B', 'C', 'F', 'G', 'H', 'J', 'L', 'O', 'P', 'Q', 'U', 'W', 'X']

def clean(callsigns, bad):
    removeline = 0

    for line in callsigns:
        for character in line:
             if character in bad:
                 removeline = 1
        if removeline == 1:
            lines.remove(line)
            removeline = 0
    return callsigns

for x in range (0, 11):
    lines = clean(lines, bad_letters)   

print (len(lines))

Tags: 文件项目inclean列表forifline
2条回答

当您在lines数组上循环(即迭代)时,您正在更改(即变异)它。这从来不是一个好主意,因为这意味着你在阅读时正在改变某些东西,这会导致你跳过行,而不是在第一时间删除它们。你知道吗

有很多方法可以解决这个问题。在下面的示例中,我们跟踪要删除的行,并在一个单独的循环中删除它们,这样索引就不会改变。你知道吗

with open(fname) as f:
    lines = f.read().splitlines()

bad_letters = ['B', 'C', 'F', 'G', 'H', 'J', 'L', 'O', 'P', 'Q', 'U', 'W', 'X']

def clean(callsigns, bad):
    removeline = 0
    to_remove = []
    for line_i, line in enumerate(callsigns):
      for b in bad:
        if b in line:
          # We're removing this line, take note of it.
          to_remove.append(line_i)
          break
    # Remove the lines in a second step. Reverse it so the indices don't change.
    for r in reversed(to_remove):
      del callsigns[r]

    return callsigns

for x in range (0, 11):
    lines = clean(lines, bad_letters)   

将要保留在单独列表中的名称保存。。也许是这个方式:-你知道吗

with open(fname) as f:
    lines = f.read().splitlines()

bad_letters = ['B', 'C', 'F', 'G', 'H', 'J', 'L', 'O', 'P', 'Q', 'U', 'W', 'X']

def clean(callsigns, bad):
    valid = [i for i in callsigns if not any(j in i for j in bad)]
    return valid

valid_names = clean(lines,bad_letters)

print (len(valid_names))

相关问题 更多 >

    热门问题