【问题标题】:python nested loop using loops and filespython嵌套循环使用循环和文件
【发布时间】:2014-08-26 16:48:04
【问题描述】:

我有一个似乎不起作用的嵌套 for 循环。内部循环变量不会随着外部循环的执行而更新。

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 时,外部循环会跟踪它,但由于某种原因,内部循环并且只有第一项被附加到列表中

【问题讨论】:

  • 您也可以使用file.seek(0) 回到文件开头。
  • 我对双嵌套循环所做的是同时扫描一个文件和另一个文件,然后使用字段的 id 将其与另一个文件进行比较以提取某些数据,但由于某种原因它是不工作。基本上我正在模拟数据库连接

标签: python list for-loop


【解决方案1】:

您正在使用

迭代文件对象
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")

【讨论】:

  • 但外循环 id 在第二次迭代时设置为 002,这应该与内循环中的 002 匹配......对吗?
  • 我对双嵌套循环所做的是同时扫描一个文件和另一个文件,然后使用字段的 id 将其与另一个文件进行比较以提取某些数据,但由于某种原因它是不工作。基本上我正在模拟数据库连接
  • @robertrocha 我的方法完全一样。你试过了吗?
猜你喜欢
  • 1970-01-01
  • 2015-04-16
  • 1970-01-01
  • 1970-01-01
  • 2021-12-11
  • 2016-11-15
  • 2010-12-21
  • 2017-04-24
  • 1970-01-01
相关资源
最近更新 更多