[英]Python: Why is this for loop exiting after the first iteration?
我正在嘗試做的事情:我正在從csv導入並試圖遍歷數據以檢查是否匹配。
我嘗試過的事情:我正在嘗試嵌套的for循環,以遍歷較大的列表,並檢查較小列表中的每個項目。
僅供參考,“農葯名稱”是d_reader文件中列的標題,因此它是鍵名稱。
agqfile=open("GCLC-USA-1.csv")
csv_a=csv.reader(agqfile)
d_reader=csv.DictReader(open("Pesticide_output.csv"))
for row in d_reader:
# print (row['Pesticide Name'])
for chem in csv_a:
print(chem[0],row['Pesticide Name'])
if chem[0] in row['Pesticide Name']:
print(chem[0],"found in ",row['Pesticide Name'])
# print(row['Pesticide Name'])
我的期望:外循環在完成之前不應該退出,但是在第一次迭代之后就退出。 但是,如果我在第二個(嵌套的)for循環之前放置一個print語句,它將打印每次迭代。
我不了解這種行為! 請您幫我解釋一下嗎?
我試圖使這個問題盡可能簡短,但是如果您需要更多信息,例如數據樣本或打印出數據類型,那么我可以提供此信息。
內部循環在第一個外部迭代中耗盡了文件對象csv_a
,因此其他外部行從不進入內部循環。 您必須將內容存儲在列表中:
agqfile=open("GCLC-USA-1.csv")
csv_a = list(csv.reader(agqfile))
d_reader=csv.DictReader(open("Pesticide_output.csv"))
for row in d_reader:
# print (row['Pesticide Name'])
for chem in csv_a:
print(chem[0],row['Pesticide Name'])
if chem[0] in row['Pesticide Name']:
print(chem[0],"found in ",row['Pesticide Name'])
# print(row['Pesticide Name'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.