我正在尝试创建一个可以平均汽车速度的python程序。然而,它们是不同的道路,这些速度被发现(这些用数字0-9表示)文件可以有任何道路编号,可以是任何速度。
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)
我需要弄清楚如何平均道路上的速度数。
答案 0 :(得分:2)
您需要做的是跟踪每条道路的所有速度 ,而不仅仅是所有速度列表和所有道路列表。
执行此操作的一种方法是使用字典:键是道路,值是该道路的速度列表或集*。您可以使用collections.defaultdict(list)
(或…(set)
)来轻松构建。
但是,你还需要知道每个速度都适合哪条路。你写东西的方式,你只是将每个单词视为一个完全独立的东西,忽略了它们成对出现的事实(以及其他有用的东西,比如每条线上总是只有一对),意味着你无法知道哪个与哪个相关。
如果文件格式确实如上所述,您可以更简单地做到这一点:而不是循环current_line
,使用current_line[0]
是道路而current_line[1]
是道路的事实速度。像这样:
road_speeds = collections.defaultdict(list)
# ...
# ... inside the loop
road, speed = current_line.split()
road = int(road)
speed = int(speed.rstrip('km'))
road_speeds[road].append(speed)
现在,当你完成整个事情时,你会看到一个类似这样的词典:
{0: [40, 67], 2: [45, 23], 1: [30]}
那么,你如何获得每条道路的平均速度?
for road, speeds in road_speeds.items():
average_speed = sum(speeds) / len(speeds)
print(road, average_speed)
请注意,如果你有Python 3.4+,你可能会发现使用statistics.mean
更可读或更明确,而不是将sum
除以len
。
*您如何知道是否使用集合或列表?基本上,如果从概念上讲不同地处理重复项,或者考虑条目的顺序有意义,那么你有一个列表;否则,你有一套。在这种情况下,如果在同一条道路上有两次相同速度的旅行,你仍然可能想要考虑它们不同的旅行,如DSM所指出的那样,所以列表可能在这里更有意义。
答案 1 :(得分:1)
collections.defaultdict和collections.Counter会很有用:
from collections import defaultdict,Counter
d = defaultdict(float)
count = Counter() # get count of all times the road appears in the file
with open("in.txt") as f:
for line in f:
rd, speed = line.rstrip().split()
d[rd] += float(speed.rstrip("km")) # sum km for each road/key
count.update(rd)
for k, v in d.items():
print("Road {} average = {}".format(k,v/count[k])) # divide sum by times road appears
Road 1 average = 30.0
Road 0 average = 53.5
Road 2 average = 34.0