Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何计算python中元组列表的平均值?_Python_Statistics_Python 2.7_Finance_Stocks - Fatal编程技术网

如何计算python中元组列表的平均值?

如何计算python中元组列表的平均值?,python,statistics,python-2.7,finance,stocks,Python,Statistics,Python 2.7,Finance,Stocks,我有一个元组列表,格式如下: [(证券、支付的价格、购买的股份数量)…] 我想合并数据。这样每个证券只列出一次 [(证券名称、支付的平均价格、持有的股份数量),…]你想做什么还不是很清楚。一些示例代码以及一些您尝试过的信息会有所帮助。即使你的方法完全错误,它也会让我们对你的目标有一个模糊的认识 同时,也许numpy的numpy.mean函数适合您的问题?我建议将元组列表转换为numpy数组,然后在所述数组的切片上应用mean函数 这就是说,它对任何类似列表的数据结构都有效,并且您可以指定要沿哪个

我有一个元组列表,格式如下:

[(证券、支付的价格、购买的股份数量)…]

我想合并数据。这样每个证券只列出一次


[(证券名称、支付的平均价格、持有的股份数量),…]

你想做什么还不是很清楚。一些示例代码以及一些您尝试过的信息会有所帮助。即使你的方法完全错误,它也会让我们对你的目标有一个模糊的认识

同时,也许numpy的
numpy.mean
函数适合您的问题?我建议将元组列表转换为numpy数组,然后在所述数组的切片上应用mean函数

这就是说,它对任何类似列表的数据结构都有效,并且您可以指定要沿哪个访问执行平均值

编辑:

{'AAPL': [638.416, 200], 'OCZ': [5.20855, 39780], 'FOSL': [52.033, 1000], 'MSFT': [39.458, 1000]}
根据我收集的信息,元组列表以以下方式组织数据:

(name, dollar ammount, weight)
我首先使用numpy将元组列表转换为数组。从中,在第一列中找到唯一的值(名称):

现在计算每个标记的平均值

meandic = {}
for element in unique_tags:
   tags = np.nonzero(a[0,:] == element)  # identify which lines are tagged with element
   meandic[element] = np.mean([t(1) * t(2) for t in a[tags]])

请注意,此代码未经测试。我可能弄错了一些小细节。如果你想不出什么,请留下评论,我很乐意纠正我的错误。您必须删除“$”并在必要时将字符串转换为浮点数。

我使用了
字典作为输出

lis=[('MSFT', '$39.458', '1,000'), ('AAPL', '$638.416', '200'), ('FOSL', '$52.033', '1,000'), ('OCZ', '$5.26', '34,480'), ('OCZ', '$5.1571', '5,300')]

dic={}
for x in lis:
    if x[0] not in dic:
     price=float(x[1].strip('$'))
     nos=int("".join(x[2].split(',')))
     #print(nos)
     dic[x[0]]=[price,nos]
    else:
     price=float(x[1].strip('$'))
     nos=int("".join(x[2].split(',')))
     dic[x[0]][1]+=nos
     dic[x[0]][0]=(dic[x[0]][0]+price)/2
print(dic)    
输出:

{'AAPL': [638.416, 200], 'OCZ': [5.20855, 39780], 'FOSL': [52.033, 1000], 'MSFT': [39.458, 1000]}
给你:

the_list = [('msft', '$31', 5), ('msft','$32', 10), ('aapl', '$100', 1)]
clean_list = map (lambda x: (x[0],float (x[1][1:]), int(x[2])), the_list)
out = {}

for name, price, shares in clean_list:
    if not name in out:
        out[name] = [price, shares]
    else:
        out[name][0] += price * shares
        out[name][1] += shares

# put the output in the requested format
# not forgetting to calculate avg price paid
# out contains total # shares and total price paid

nice_out = [ (name, "$%0.2f" % (out[name][0] / out[name][1]), out[name][1])
              for name in out.keys()]

print nice_out
>>> [('aapl', '$100.00', 1), ('msft', '$23.40', 15)]

+1.我搞砸了defaultdict,什么都搞不清楚。如果我有[(msft,$31,5),(msft,$32,10),(aapl,$100,1)],我应该看到[(msft,31.75,15),(aapl,100,1)]的输出。看到了吗?@ZacharyBurt,恐怕我不明白你的例子。你需要更加明确。请发布您已经尝试编写的代码。在你这么做之前我们帮不了你。我会等几天,然后发布一个因果报应bounty@ZacharyBurt好的,这是你的答案。请告诉我这是否有效!
>>> lis
[('MSFT', '$39.458', '1,000'), ('AAPL', '$638.416', '200'), ('FOSL', '$52.033', '1,000'), ('OCZ', '$5.26', '34,480'), ('OCZ', '$5.1571', '5,300')]
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for i in lis:
...    amt = float(i[1].strip('$'))
...    num = int(i[2].replace(",", ""))
...    d[i[0]].append((amt,num))
... 
>>> for i in d.iteritems():
...   average_price = sum([s[0] for s in i[1]])/len([s[0] for s in i[1]])
...   total_shares = sum([s[1] for s in i[1]])
...   print (i[0],average_price,total_shares)
... 
('AAPL', 638.416, 200)
('OCZ', 5.20855, 39780)
('FOSL', 52.033, 1000)
('MSFT', 39.458, 1000)
the_list = [('msft', '$31', 5), ('msft','$32', 10), ('aapl', '$100', 1)]
clean_list = map (lambda x: (x[0],float (x[1][1:]), int(x[2])), the_list)
out = {}

for name, price, shares in clean_list:
    if not name in out:
        out[name] = [price, shares]
    else:
        out[name][0] += price * shares
        out[name][1] += shares

# put the output in the requested format
# not forgetting to calculate avg price paid
# out contains total # shares and total price paid

nice_out = [ (name, "$%0.2f" % (out[name][0] / out[name][1]), out[name][1])
              for name in out.keys()]

print nice_out
>>> [('aapl', '$100.00', 1), ('msft', '$23.40', 15)]