Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ms-access/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何打印列表中元组平均值的消息_Python_Python 3.x_Tuples - Fatal编程技术网

Python 如何打印列表中元组平均值的消息

Python 如何打印列表中元组平均值的消息,python,python-3.x,tuples,Python,Python 3.x,Tuples,我的代码是打印列表中元组的平均值,如果列表为空,则返回None。现在这是我的代码 def average_vehicles(vehicle_records): """Return average of vehicles""" summ = 0 num = 0 average = 0 if vehicle_records != []: for value in vehicle_records:

我的代码是打印列表中元组的平均值,如果列表为空,则返回None。现在这是我的代码

def average_vehicles(vehicle_records):
    """Return average of vehicles"""
    summ = 0
    num = 0
    average = 0
    if vehicle_records != []:
        for value in vehicle_records:            
            summ += value[1]
            num += 1
        average = summ / num
    else:
        average  = "None" 
    return average
我获得了此测试代码的正确输出:

some_records = [('2010-01-01',100),
            ('2010-01-02',200),
            ('2010-01-03',300)]
avg = average_vehicles(some_records)
print(avg)
然而,我不能让它为下面的测试代码打印“OK”,我也不确定为什么它在其他一切看起来都正常的情况下不能完成工作,请有人帮忙好吗

some_records = []
avg = average_vehicles(some_records)
if avg is None:
   print('OK')
else:
   print('The function should return a None value')

None
“None”
不是一回事。

None不应该是字符串,而应该是None对象。
将以下行
average=“None”
更改为
average=None
,它应该可以工作。

您返回的是字符串
“None”
,而不是对象
None

some_records = []
avg = average_vehicles(some_records)
if avg == "None":
   print('OK')
else:
   print('The function should return a None value')
说明:


当我们打印
avg
类型时,它的类型是
str
,但如果我们选中
avg为None
,则在此
None
中,它的类型是
Nonetype
。因此,我们需要使用“None”作为
avg==“None”

进行检查,因为您将返回字符串
“None”
,而不是
None
。将else中的代码更改为
average=None
,它应该可以工作。默认情况下,平均值为
0
或某个值!它永远不会是
“None”
,也不会是None对象!此外,不需要计算循环中的和。您可以使用内置的
sum
并将
average\u vehicles
功能简化为一行:
返回sum(rec[1]用于车辆记录中的rec)/len(车辆记录),如果车辆记录中没有其他记录
some_records = []
avg = average_vehicles(some_records)
if avg == 'None':
   print('OK')
else:
   print('The function should return a None value')