1 回答

TA貢獻1863條經(jīng)驗 獲得超2個贊
您可以嘗試?yán)米值鋪硪淮胃櫮械脑路?,這樣您就不必多次循環(huán):
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))
結(jié)果:
['N/A', 182.0, 246.66666666666666, 236.25, 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A']
從復(fù)雜性的角度來看,這基本上與您所能獲得的一樣高效。您修改后顯示的代碼的復(fù)雜性O(shè)(12 * n)為O(12 + N). 一個并不比另一個效率低得多,但是如果不遍歷整個數(shù)組就無法準(zhǔn)確找到這些平均值,因此您只能使用O(N).
添加回答
舉報