You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

遍历二维数组匹配CSV数据时仅检测首个元素,求修正方案

问题解决:遍历二维数组匹配CSV数据

你的代码只检查第一个数组元素就停止,核心原因是csv.reader返回的是迭代器——第一次遍历location_file后,这个迭代器就被耗尽了,后续循环再去遍历它时,已经没有任何数据可以读取。

下面提供两种可行的修改方案:

方案一:提前读取全部CSV内容(适合小文件)

先把CSV的所有行读到列表中,这样可以重复遍历这些行来匹配数组元素:

import csv

# 用with语句安全读取CSV并转为列表
with open('Location.csv', "r") as f:
    location_rows = list(csv.reader(f, delimiter=";"))

test_array = [['16', '2'],['19', '2'],['16', '8'],['16', '9'],['16', '10'],['11', '2'],['11', '6'],['1', '12'],['1', '5'],['1', '4'],['4', '4'],['4', '6'],['14', '2'],['14', '7']]

# 直接遍历test_array的每个元素,无需手动索引
for item in test_array:
    for row in location_rows:
        if item[0] == row[2] and item[1] == row[3]:
            print(row[0])

方案二:用集合优化匹配逻辑(适合大文件)

如果CSV文件数据量较大,重复遍历会拖慢效率。可以把test_array转为元组集合(列表无法哈希,元组可以),只遍历一次CSV就能完成所有匹配:

import csv

test_array = [['16', '2'],['19', '2'],['16', '8'],['16', '9'],['16', '10'],['11', '2'],['11', '6'],['1', '12'],['1', '5'],['1', '4'],['4', '4'],['4', '6'],['14', '2'],['14', '7']]
# 把二维数组元素转为元组并存入集合,加快查找速度
test_set = set(tuple(item) for item in test_array)

with open('Location.csv', "r") as f:
    location_file = csv.reader(f, delimiter=";")
    # 仅遍历一次CSV文件
    for row in location_file:
        current_match = (row[2], row[3])
        if current_match in test_set:
            print(row[0])

另外注意:使用with语句打开文件会自动处理文件关闭,比直接open更安全规范,建议始终使用这种方式。

内容的提问来源于stack exchange,提问作者user19912082

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:06:24