我想确保twist_data
仅获取整数列表作为参数,并添加单元测试。
def twist_data(n):
n=list(n)
a=[]
b=[]
for i in n:
if i<=0:
a.append(i)
if i>0:
b.append(i)
n=[len(a),sum(b)]
return n
gum=[2,4,5,-6,-7,]
print (twist_data (gum))
答案 0 :(得分:0)
def all_ints(numbers):
return all(isinstance(number, int) for number in numbers)
def validate_list(numbers):
return all((isinstance(numbers, list), all_ints(numbers))
def twist_data(numbers):
if not validate_list(numbers):
raise TypeError('"numbers" must be of type "list", where all elements integers')
positives, negatives = [], []
for number in numbers:
if number <= 0:
negatives.append(number)
if i > 0:
positives.append(number)
return [len(negatives), sum(positives)]
虽然Pythonic通常不进行显式类型检查,但有时它是不可避免的。这是一个非常直接的方法。然而,要求宽恕比要求许可更容易,所以这是另一种可能性:
def twist_data(numbers):
positives, negatives = [], []
try:
for number in numbers:
if number <= 0:
negatives.append(number)
if i > 0:
positives.append(number)
return [len(negatives), sum(positives)]
except TypeError:
raise TypeError('"numbers" must be of type "list", where all elements integers')
如果您尝试在不可比较的类型之间进行比较,则会引发TypeError
。然后,您可以捕获异常并使用您自己的消息重新加载。
还要尽量避免使用单字母变量名。跟踪正在发生的事情会更加容易。