好的,我需要通过以下doctests:
"""
Does it work on files where no error checking is needed on the fields
>>> sumRows("rows1.csv") == {'tim': 36.0, 'bob': 11.0, 'anna': 54.0}
True
Does it ignore headers if requested?
>>> sumRows("rows1.csv", header=True) == {'tim': 36.0, 'anna': 54.0}
True
Does it work on files with empty fields or fields which aren't numbers?
>>> sumRows("rows2.csv") == {'tim': 24.0, 'bob': 11.0, 'anna': 13.0}
True
"""
我创建了这段代码,在我眼里看起来不错,但它只是拒绝在doctests中返回“True”而只会返回“False”
def sumRows(filename, header=False):
x = {}
import csv
rdr = csv.reader(open(filename))
for l, row in enumerate(rdr):
if header == True and l == 0:
pass
else:
amount = 0
for num in row[1:0]:
if num.isdigit():
amount += int(num)
x[row[0]] = amount
return x
知道问题是什么?
答案 0 :(得分:1)
似乎是这一行:
for num in row[1:0]:
永远不会做任何事情,因为你试图遍历一个空列表。
list[1:0] # from position 1 (included) to 0 (excluded) is always []
答案 1 :(得分:0)
Doctests不比较值,他们比较字符串。
虽然以下比较为True
,但作为doctest,它将评估为False
>>> {'bob': 11.0, 'anna': 54.0, 'tim': 36.0} == {'tim': 36.0, 'bob': 11.0, 'anna': 54.0}
这可能发生,因为dict
s是无序的。要将此比较作为doctest执行,您需要将值存储在有序类型中。
>>> list(sorted(sumRows('rows1.csv').items())) == list(sorted({{'tim': 36.0, 'bob': 11.0, 'anna': 54.0}}.items()))
True