Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.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_Average - Fatal编程技术网

需要帮助查找python中的平均值吗

需要帮助查找python中的平均值吗,python,average,Python,Average,字段[quant]中198和272范围内的数字的平均值是多少 quant 95 189 176 200 177 340 205 203 284 88 109 83 360 67 250 56 111 439 354 143 这是我试过的代码。上面是[quant]字段,我需要从中找到平均值 word_file = open('300000a.csv','r') firstLine = True for line in word_file: if firstLine:

字段[quant]中198和272范围内的数字的平均值是多少

quant
95
189
176
200
177
340
205
203
284
88
109
83
360
67
250
56
111
439
354
143
这是我试过的代码。上面是[quant]字段,我需要从中找到平均值

word_file = open('300000a.csv','r')

firstLine = True 
for line in word_file:
    if firstLine:
        firstLine = False
        continue
    line = line.strip()
    line = line.split (",")
    field = int(line[0])

TotalMetalCount +=1
if  field >198 or field <272:
  metalCounts += 1
else:
    metalCounts = 1


countT +=1
if field >198 or field <272:
        count += 1

您可以使用并除以计算列表的平均值

如果只需要获取几个特定项并根据这些项提取平均值,则可以对数组进行切片

print(float(sum(my_list[198:272]))/len(my_list[198:272]))
如果您有一个包含字符串而不是整数的列表,则需要先将其转换为整数列表,然后才能使用sum

my_list_of_integers = [int(i) for i in my_list[198:272]
print(float(sum(my_list_of_integers))/len(my_list_of_integers]))
如果你要做更多的数字运算,你应该使用。然后将有多种方式将CSV文件作为数组读取。这些数组有一个.mean方法,它实现了您所认为的功能


但如果你不做更多的数字运算,那么@eandersson的答案就更符合比例。

@GrijeshChauhan请不要建议减少你可以使用的数字sum@jamylak:…同意,谢谢!:@莱维斯基是的。。。不太清楚为什么又有人问。无论如何,它必须是类/作业的一部分,但要求更好-因此建议OP阅读该类/作业…我已经阅读了您的代码很多次,但我不知道您的代码和变量的含义。看起来,@user2370772不需要获取所有元素,而只需要获取其中的一部分。所以过滤列表将对himAh有好处。是的,这可能是真的。我尝试了第二个代码,它出现了错误无效语法,它用红色显示INT。。。我该怎么办?我更新了示例,以防您使用Python3。@eandersson,在Python2中,和的行为会很糟糕,因为它可能会进行整数除法。将两者单独转换为浮动更安全。
my_list_of_integers = [int(i) for i in my_list[198:272]
print(float(sum(my_list_of_integers))/len(my_list_of_integers]))