0

我有一段代码用于比较两个列表(从 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

有人可以帮忙吗?谢谢!

4

2 回答 2

3

您没有default_value变量。

就像你的错误说:

NameError: global name 'default_value' is not defined

你应该把这样的东西:

default_value = None

以上代码。

于 2013-07-18T08:28:04.170 回答
1

您的表现在有一些空行,因此条件

如果长度(行)

is now Falseand default_valueis used but not found。

于 2013-07-18T08:44:04.843 回答