gpt4 book ai didi

Python:查找每个月的平均股票值(value)

转载 作者:行者123 更新时间:2023-11-28 22:55:20 25 4
gpt4 key购买 nike

基本上我有一个包含数据和价格的元组列表,例如:

[ ("2013-02-12", 200.0), ("2012-02-25", 300.0), ("2000-03-04", 100.0), ("2000-03-05", 50.0)]

该函数需要找到每个月的平均股票值(value),然后返回包含日期(月份和年份)和股票价格的元组列表。像这样的东西:

[(250.0, "02-2013"), (100.0, "03-2000"), (50.0, "03-2000")]

这是我目前的代码:

def average_data(list_of_tuples = []):

list_of_averages = []
current_year_int = 2013
current_month_int = 2
sum_float = float()
count = 0
for dd_tuple in list_of_tuples:
date_str = dd_tuple[0]
data_float = dd_tuple[1]
date_list = date_str.split("-")
year_int = int(date_list[0])
month_int = int(date_list[1])
date_year_str = "Date: " + str(month_int) + "-" + str(year_int);


if month_int != current_month_int:
average_float = sum_float / count
average_list = [date_year_str, average_float]
average_tuple = tuple(average_list)
list_of_averages.append(average_tuple)
current_month_int = month_int
sum_float += data_float


sum_float += data_float
count += 1
current_month_int = month_int
current_year_int = year_int


return list_of_averages

它返回一个平均值,但不是正确的,也许不是全部?我曾尝试查看互联网上的示例并询问我的助教(这是针对 python 类的)但无济于事。有人能指出我正确的方向吗?

编辑:根据建议,if 语句现在应该如下所示,对吗?

    if month_int != current_month_int:
average_float = sum_float / count
average_list = [date_year_str, average_float]
average_tuple = tuple(average_list)
list_of_averages.append(average_tuple)
current_month_int = month_int
sum_float = 0.0
count = 0
sum_float += data_float
count += 1

编辑:感谢大家的帮助!我现在已经运行了代码。

最佳答案

>>> lis = [ ("2013-02-12", 200.0), ("2012-02-25", 300.0), ("2000-03-04", 100.0), ("2000-03-05", 50.0)]
>>> from collections import defaultdict
>>> dic = defaultdict(list)
>>> for k,val in lis:
key = "-".join(k.split('-')[:-1][::-1])
dic[key].append(val)
...
>>> [(sum(v)/float(len(v)),k) for k,v in dic.items()]

[(200.0, '02-2013'), (300.0, '02-2012'), (75.0, '03-2000')]

上述代码的简化版本:

lis = [ ("2013-02-12", 200.0), ("2012-02-25", 300.0), ("2000-03-04", 100.0), ("2000-03-05", 50.0)]
dic = {}
for date, val in lis:
#split the date string at '-' and assign the first 2 items to year,month
year, month = date.split('-')[:2]
#now check if (month,year) is there in the dict
if (month, year) not in dic:
#if the tuple was not found then initialise one with an empty list
dic[month,year] = []

dic[month,year].append(val) # append val to the (month,year) key

print dic
#Now iterate over key,value items and do some calculations to get the desired output
sol =[]
for key, val in dic.items():
new_key = "-".join(key)
avg = sum(val) / len(val)
sol.append((avg, new_key))
print sol

输出:

#print dic
{('03', '2000'): [100.0, 50.0],
('02', '2013'): [200.0],
('02', '2012'): [300.0]}
#print sol
[(75.0, '03-2000'), (200.0, '02-2013'), (300.0, '02-2012')]

关于Python:查找每个月的平均股票值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17016731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com