我使用以下代码在csv文件的特定列中搜索id列表
#!/usr/bin/python
import csv
import sys
with open(r"C:TestinputTest.csv", newline = '') as inputFile:
inputReader = csv.reader(inputFile, delimiter=",")
idFile = open(r"C:Testtestids.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
知道为什么第二个循环(嵌套循环)不是每次都运行吗?
就像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是否为"in"那本字典:
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