Python 3.x 从CSV中一次搜索一行字符串
我有两个CSV文件,第一个是搜索项,另一个是某种数据库。我想在两个文件之间实现线性搜索 我正在使用python 3.6 这是我的密码:Python 3.x 从CSV中一次搜索一行字符串,python-3.x,csv,Python 3.x,Csv,我有两个CSV文件,第一个是搜索项,另一个是某种数据库。我想在两个文件之间实现线性搜索 我正在使用python 3.6 这是我的密码: import csv macs = [] brands = [] macxs = [] with open('example.csv') as csvfile: readcsv = csv.reader(csvfile, delimiter=',') for row in readcsv: mac = row[0]
import csv
macs = []
brands = []
macxs = []
with open('example.csv') as csvfile:
readcsv = csv.reader(csvfile, delimiter=',')
for row in readcsv:
mac = row[0]
brand = row[1]
macs.append(mac)
brands.append(brand)
def macslice(slice):
return slice[:8]
with open('eggsample.csv') as csvfile2:
readcsv2 = csv.reader(csvfile2, delimiter=',')
for row in readcsv2:
macx = macslice(row[0])
macxs.append(macx)
def compare():
i=0
while i < len(macs):
if (macs[i] == macxs[i]):
print("FOUND", brands[i])
i += 1
else:
print("NOT FOUND")
i += 1
def compare2():
i=0
while i < len(macxs):
for x in macxs:
if (macs[i] == macxs[i]):
print("FOUND", brands[i]+" "+ macs[i])
i += 1
else:
print("BRAND not found for: ",macxs[i] )
i += 1
compare2()
导入csv
macs=[]
品牌=[]
macxs=[]
将open('example.csv')作为csvfile:
readcsv=csv.reader(csvfile,分隔符=',')
对于readcsv中的行:
mac=行[0]
品牌=行[1]
macs.append(mac)
品牌。附加(品牌)
def macslice(切片):
返回片[:8]
打开('eggsample.csv')作为csvfile2:
readcsv2=csv.reader(csvfile2,分隔符=',')
对于readcsv2中的行:
macx=macslice(第[0]行)
macxs.append(macx)
def compare():
i=0
而我
我的代码没有进行线性搜索,而是将第一个CSV中的第一行与第二个CSV中的第一行进行比较,依此类推,直到两个CSV结束
我期望某种线性搜索,逐行搜索,并在第一个CSV中返回行的条件
希望我的描述能帮助解决我的问题。问题在于您的比较,因为您正在与索引
i
进行比较
经验法则,您在比较中使用x
的位置2
切换到:
def compare2():
for y in macs:
for x in macxs:
if x==y:
print("FOUND", x+" "+ y)
else:
print("BRAND not found for: ",y )
compare2()
或者类似的东西 问题在于您的比较,因为您正在与索引
i
进行比较
经验法则,您在比较中使用x
的位置2
切换到:
def compare2():
for y in macs:
for x in macxs:
if x==y:
print("FOUND", x+" "+ y)
else:
print("BRAND not found for: ",y )
compare2()
或者类似的东西 你能提供一个简单的虚拟(每个文件可能只有一行)的你要比较的样本吗?你能提供一个简单的虚拟(每个文件可能只有一行)的你要比较的样本吗?