我正在嘗試創建一個能夠平均車速的python程序。然而,他們是不同的道路,這種速度可以找到(這些都是數字0-9表示)文件可以有任何道路號碼,可以是任何速度。Python文件,取文件並找到平均值
Example1.txt
0 40km
1 30km
0 67km
2 45km
2 23km
我想創建與走輔路的平均
average of 1 = 30
average of 0 = 35
等,文件可以包含然而,許多配對和道路將是數字0-9 這之間的程序我到目前爲止:
def traffic_summary(filename):
in_file = open(filename)
lines = in_file.readlines()
in_file.close()
return lines
def calc_traffic_avg(lines):
# Find out how long the file is
total_lines = len(lines)
# For every file line, find the charity and the amount contributed
avg = 0 # Nums + however many/How ever many integers there are
road_nums = []
master = []
road_speeds = []
for i in range(1, total_lines): # Omits the title lines
current_line = lines[i].rstrip("\n") #Removes the new line
current_line = current_line.split()
for j in range(len(current_line)):
current_word = current_line[j]
if "km" in current_word:
position = j
amount = int(current_word.rstrip('km'))
road_speeds.append(amount)
if not "km" in current_word:
road_nums.append(int(current_word))
print(road_nums, road_speeds)
我需要弄清楚如何平均道路上的速度數量。
你究竟想知道什麼?要找到平均值,您需要爲特定道路加上所有不同的速度,然後除以構成總和的那些速度。 – martineau 2014-10-29 01:35:42