I have a piece of code that's meant to compare two lists (which are read from CSV files) and return the items that are in A and not in B and vice versa. Here's what I've got:
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!"
It used to run just fine, until I got this error:
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
Can anyone please help ? Thanks!
You do not have a default_value
variable.
just like your error says:
NameError: global name 'default_value' is not defined
You should put something like:
default_value = None
Above the code.
Your tables have now some empty rows, thus the condition
if len(row)
is now False
and default_value
is used but not found.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.