[英]function that takes a list of intergers from a textfile and return the min, max,and avg
我有一個這樣的清單
[['min: 1', '2', '3', '5', '6\n'],
['max: 1', '2', '3', '5', '6\n'],
['avg: 1', '2', '3', '5', '6']]
在文本文件上。
我想計算最小,最大和平均值,但我在刪除列表中的最小,最大和平均值時遇到了麻煩。
infile = open('input.txt', 'r+')
lisnum = []
for line in infile:
listnum.append(line.split(','))
for i in listnum:
print i
infile.close()
def minimum(mi):
min_value = min(mi)
return min_value
def maximum(ma):
max_value = max(ma)
return max_value
def average(avg):
sum = 0
for x in av:
sum+=x
return(sum/len(av))
print listnum
a = [i.split(':')[0] for i in listnum]
print a
print minimum(listnum)
print maximum(listnum)
print average(listnum)
似乎您在非CSV文件(逗號分隔值)上使用了split(',')
)。 您可以使用split(':')[1]
來單獨處理列表中的第一個值,以獲取:
之后的部分,但我建議使用正則表達式來獲取列表中的所有數字:
>>> line = 'max: 1,2,3,5,6\n'
>>> re.findall('\d+', line)
['1', '2', '3', '5', '6']
>>> nums = [int(x) for x in re.findall('\d+', line)]
>>> min(nums)
1
同樣,似乎您正在將函數應用到整個列表列表,而不只是應用到相應的行。 為了得到,例如, max
的“最大”行,使用print maximum(listnum[1])
似乎您仍然對此有疑問。 就像我說的,你不能分割的整個列表,
因為整個列表不會被分開,
。 您可以使用正則表達式來獲得這兩個操作和數字,或者您也可以通過先被分割:
然后 ,
。 嘗試一下:
operations = {"sum": sum, "min": min, "max": max,
"avg": lambda lst: float(sum(lst))/len(lst)}
with open("input.txt") as f:
for line in f:
op, numbers = line.split(":")
op = op.strip().lower()
numbers = [float(n) for n in numbers.split(",")]
if op in operations:
print("%s of %r is %f" % (op, numbers, operations[op](numbers)))
else:
print("Don't know how to do %s" % op)
輸出:
min of [1.0, 2.0, 3.0, 5.0, 6.0] is 1.000000
max of [1.0, 2.0, 3.0, 5.0, 6.0] is 6.000000
avg of [1.0, 2.0, 3.0, 5.0, 6.0] is 3.400000
Don't know how to do p90
sum of [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] is 21.000000
Don't know how to do p70
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.