1 回答
TA贡献1863条经验 获得超2个赞
您可以尝试利用字典来一次跟踪您所有的月份,这样您就不必多次循环:
from collections import defaultdict
my_list = [(2, 181), (2, 183), (3, 376), (4, 205)]
input_tuple = my_list
#Function to calculate and report back the average duration for each month
def average_duration(input_tuple):
months = defaultdict(list)
output_tuple = []
for month, value in input_tuple:
months[month].append(value)
overall_report = []
for month in range(12):
report = months[month + 1]
if not report:
output_tuple.append("N/A")
else:
overall_report.extend(report)
output_tuple.append(sum(overall_report)/len(overall_report))
return output_tuple
print(average_duration(input_tuple))
结果:
['N/A', 182.0, 246.66666666666666, 236.25, 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A']
从复杂性的角度来看,这基本上与您所能获得的一样高效。您修改后显示的代码的复杂性O(12 * n)为O(12 + N). 一个并不比另一个效率低得多,但是如果不遍历整个数组就无法准确找到这些平均值,因此您只能使用O(N).
添加回答
举报