使用csv和列表文件的Python嵌套循环

p1iqtdky  于 2023-01-18  发布在  Python
关注(0)|答案(1)|浏览(137)

我使用下面的代码在csv文件的特定列中搜索ID列表

#!/usr/bin/python

import csv
import sys

with open(r"C:\Test\inputTest.csv", newline = '') as inputFile:
   inputReader   = csv.reader(inputFile, delimiter=",")
   idFile = open(r"C:\Test\testids.txt")
   loopcounter = 1
   for inputRow in inputReader:
    loopcountr+= 1
    print (loopcounter)
    inputString = inputRow[18]
    for id in idFile:
        print ("id: ", id)
        print ("InputString", inputString)
        result = inputString.find(id)
        print (result)

但是带有id文件的嵌套循环只运行一次,之后就不再运行了。
输出:

1
 id:  123388

InputString  ID
-1
 id:  112233

InputString  ID
-1
 id:  141414
InputString  ID
-1
2
3
4
5
6
7
8
9
10

知道为什么第二个循环(嵌套循环)不是每次都运行吗?

ifmq2ha2

ifmq2ha21#

就像Tim Roberts在评论中提到的,“您应该将idFile读入列表,然后迭代列表。”
您可以将测试ID读入一个列表,如下所示:

with open("test_ids.txt") as f:
    test_ids = []
    for line in f:
        test_ids.append(line.strip())

或者,如果你对Python中的列表解析很熟悉,那么这是等价的:

with open("test_ids.txt") as f:
    test_ids = [x.strip() for x in f.readlines()]

然后,当您阅读CSV文件时(大概),您可以将CSV中的一些数据与测试ID进行比较。
这可能看起来像下面这样,我还使用enumerate()来计算迭代次数:

with open("input.csv", newline="") as f:
    reader = csv.reader(f)
    next(reader)  # discard header

    for i, row in enumerate(reader, 1):
        input_id = row[0]  # don't use 'id', it's a reserved word
        name = row[1]
        print(f"row #:{i}, input_ID:{input_id}, Name:{name}")

        for test_id in test_ids:
            if test_id == input_id:
                print(f"  {name} matches test_ID {test_id}")

我模拟了这个数据,CSV的ID在第一列,row[0]来自上面的代码:

test_ids.txt
============
105
108

input.csv
=========
ID,Name
105,Alice
106,Bing
107,Che
108,Dee

当我运行代码时,我得到:

row #:1, input_ID:105, Name:Alice
  Alice matches test_ID 105
row #:2, input_ID:106, Name:Bing
row #:3, input_ID:107, Name:Che
row #:4, input_ID:108, Name:Dee
  Dee matches test_ID 108

这就是实现嵌套循环的方法。
如果你习惯于在字典中进行“查找”,你可以摆脱嵌套循环:

with open("test_ids.txt") as f:
    test_ids = {}
    for line in f:
        test_ids[line.strip()] = None

test_ids字典如下所示:

{'105': None, '108': None}

现在,您只需检查每个输入ID是否“在”该字典中:

with open("input.csv", newline="") as f:
    ... 
    for i, row in enumerate(reader, 1):
        ...
        if input_id in test_ids:
            print(f"  {name} found in test_IDs")

这会产生类似的输出:

row #:1, input_ID:105, Name:Alice
  Alice found in test_IDs
row #:2, input_ID:106, Name:Bing
row #:3, input_ID:107, Name:Che
row #:4, input_ID:108, Name:Dee
  Dee found in test_IDs

相关问题