python嵌套循环使用循环和文件 [英] python nested loop using loops and files

查看:160
本文介绍了python嵌套循环使用循环和文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套的for循环似乎没有工作。当执行外循环时,内循环变量不会更新。

pre $ 对于文件行:
record =行.blit(',')
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时,外层循环保持跟踪,但对于一些原因是内部循环,只有第一项被追加到列表中

解决方案

您正在迭代文件对象

  for lin in another_file:

在外循环的第一次迭代之后, another_file 被用尽了。因此,在第一次外循环迭代后内循环从不执行。



如果你想这样做,你需要像这样再次打开文件

  with open(another.txt)as another_file:
for other_file:
...

更好的是,您只能在外部循环本身之前收集必要的信息,并使用像这样的预处理数据

 #用另一个文件
创建一个带有open(another.txt)的ID作为another_file:
ids = {lin.split(',')[3] for in in another_file}

with open(mainfile.txt)as file:
for line in file :
record_id = line.split(',')[0]
mas_list.append(record_id)
#检查record_id是否来自另一个文件的ID集合
如果record_id在ids中:
mas_list.append(some data)


I have a nested for loop that doesn't seem to be working. The inner loops variable is not updating as the outer loop is executing.

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

now this works for an id of 001 but when I get to id 002 the outer loop keeps track of that but for some reason the inner loop and only the first item is appended to the list

解决方案

You are iterating the file object with

for lin in another_file:

After the first iteration of the outer loop, the another_file is exhausted. So, the inner loop never executes after the first outer loop iteration.

If you want to do it like this, you need to open the file again like this

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

Even better, you can gather only the necessary information before the outer loop itself and use the preprocessed data like this

# 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")

这篇关于python嵌套循环使用循环和文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆