Python for循环只运行一次?
该脚本将根据csv中的数据库查询包含物种名称的csv,如果两者都在,则返回。问题是,尽管它仍在阅读所有术语以进行精细搜索,但它只是在搜索第一个术语。i、 e.如果我在“p中的行”之前打印物种L,所有物种名称都会正确返回Python for循环只运行一次?,python,csv,for-loop,Python,Csv,For Loop,该脚本将根据csv中的数据库查询包含物种名称的csv,如果两者都在,则返回。问题是,尽管它仍在阅读所有术语以进行精细搜索,但它只是在搜索第一个术语。i、 e.如果我在“p中的行”之前打印物种L,所有物种名称都会正确返回 from pathlib import Path import os import csv p = csv.reader(open('Paldat.csv','r',newline=''), delimiter=',') with open('newsssssss.csv',
from pathlib import Path
import os
import csv
p = csv.reader(open('Paldat.csv','r',newline=''), delimiter=',')
with open('newsssssss.csv','r',newline='\n')as r:
for line in r:
taxons=line.split(',')
no = ['\r\n']
noo = ['\n']
if taxons == no:
continue
elif taxons == noo:
continue
else:
speciesl = []
for val in taxons:
val = val.replace('\n','')
speciesl.append(val)
g=speciesl[0].lower()
if len(speciesl) < 2:
continue
else:
s=speciesl[1].lower()
for row in p: #This loop seems to be the issue
genus = row[0].lower()
species = row[1].lower()
if g == genus and s == species:
print('Perfect match')
print(g)
elif s == species:
print(speciesl)
print('Species found')
else:
continue
else:
continue
以及Newssss.csv的一部分:
Camassia,leichtlinii
Camellia,japonica
Camellia,sinensis
Chrysanthemum,leucanthemum
Cirsium,arvense
Cissus,quadrangularis
尝试从开放行中删除换行符=“\n”。请提供预期的MRE。我们应该能够复制和粘贴一个连续的代码块,执行该文件,并再现您的问题以及跟踪问题点的输出。这让我们可以根据您的测试数据和期望的输出来测试我们的建议。显示中间结果与您预期的不同之处。你发布的代码不是最小的;由于一个私有文件,它无法运行,并且您尚未跟踪问题点。抱歉。现在,当您第一次使用p中的行在文件Paldat.csv的整个内容上循环时,应该修复此问题。在下面r上的循环中,您已经到达p的末尾,因此不再从该文件中读取任何行。非常好,谢谢!!-我把p=csv.reader…paldat.csv。。。里边是r行,很有效谢谢你的回复。同样的事情也发生了。这更多的是一个评论而不是一个答案,尤其是因为它并没有解决问题。
Camassia,leichtlinii
Camellia,japonica
Camellia,sinensis
Chrysanthemum,leucanthemum
Cirsium,arvense
Cissus,quadrangularis