我有一段代码用于比较两个列表(从CSV文件中读取)并返回A中的项而不是B中的项,反之亦然。 这就是我所拥有的:
import csv
#open CSV's and read first column with product IDs into variables pointing to lists
with open("A.csv", "rb") as f:
a = {row[0] if len(row) else default_value for row in csv.reader(f)}
with open("B.csv", "rb") as g:
b = {row[0] if len(row) else default_value for row in csv.reader(g)}
#create variables pointing to lists with unique product IDs in A and B respectively
in_a_not_b = a-b
in_b_not_a = b-a
print len(in_a_not_b), " items in A missing from B", in_a_not_b
print len(in_b_not_a), " items in B missing from A", in_b_not_a
print "done!"
它曾经运行得很好,直到我收到此错误:
Traceback (most recent call last):
File "C:/.../python - Comprare two lists", line 7, in <module>
b = {row[0] if len(row) else default_value for row in csv.reader(g)}
File "C:/.../python - Comprare two lists", line 7, in <setcomp>
b = {row[0] if len(row) else default_value for row in csv.reader(g)}
NameError: global name 'default_value' is not defined
有人可以帮忙吗? 谢谢!
答案 0 :(得分:3)
您没有default_value
变量。
就像你的错误所说:
NameError: global name 'default_value' is not defined
您应该输入类似的内容:
default_value = None
代码上方。
答案 1 :(得分:1)
您的表现在有一些空行,因此条件
如果len(行)
现在使用False
并使用default_value
但未找到。