使用循环和文件的Python嵌套循环

1 投票
1 回答
1301 浏览
提问于 2025-04-18 12:13

我有一个嵌套的循环,但它似乎不太正常。里面的循环变量在外面的循环执行时没有更新。

for line in file:
    record = line.split(',')
    id = record[0]
    mas_list.append(id)
    for lin in another_file:
        rec = lin.split(',')
        idd = rec[3]
        if idd == id:
        mas_list.append("some data")
        mas_list.append("some data")

现在这个对 id 为 001 的情况是有效的,但当我到达 id 为 002 时,外面的循环能正常跟踪这个 id,但里面的循环却只把第一个项目加到了列表里,其他的没有。

1 个回答

3

你正在用以下方式遍历文件对象:

for lin in another_file:

在外层循环的第一次迭代后,another_file 文件就被读完了。所以,内层循环在第一次外层循环后就不会再执行了。

如果你想这样做,你需要像下面这样重新打开文件:

with open("another.txt") as another_file:
    for lin in another_file:
        ...

更好的方法是,你可以在外层循环之前先收集好需要的信息,然后像下面这样使用处理过的数据:

# Create a set of ids from another file
with open("another.txt") as another_file:
    ids = {lin.split(',')[3] for lin in another_file}

with open("mainfile.txt") as file:
    for line in file:
        record_id = line.split(',')[0]
        mas_list.append(record_id)
        # Check if the record_id is in the set of ids from another file
        if record_id in ids:
            mas_list.append("some data")

撰写回答