Python字典 - 从其他值查找平均值 [英] Python Dictionary - find average of value from other values

查看:1023
本文介绍了Python字典 - 从其他值查找平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下列表

  count = 3.5,price = 2500 

count = 3 ,price = 400

count = 2,price = 3000

count = 3.5,price = 750

count = 2,price = 500

我想查找所有计数相同的平均价格。例如:

  count = 2,price = 3000 

count = 2,price = 500

3000 + 500 = 3500

3500/2 = 1750

2的平均值是1750



这是我的代码到目前为止

  avg_list = [value [average] for dictionary in dictionary_database_list] 

counter_obj = collections.Counter(count_list)

print(AVG:)

在我的counter_obj中:

print(i,counter_obj [i])
/ pre>

解决方案

我承认我不是100%清楚你在找什么,我会给它一个镜头:



当你想迭代一个事物列表并积累某些关于同一事物的信息时,一个很好的策略是使用哈希表。在Python中,我们通常对需要哈希表的算法使用 dict



收集足够的信息以获取您的列表中每个项目的平均价格,我们需要:


a)具有特定count的项目总数< b> b)具有特定计数的项目的总价格


所以让我们建立一个数据结构,将一个count映射到含有count的项目的total items和total price的单词。



我们的输入格式为:

  item_list = [
{'count':3.5,'price':2500} ,
{'count':3,'price':400},
{'count':2,'price':3000},
{'count':3.5,'price ':750},
{'count':2,'price':500},
]

现在我们来映射关于总项目和总价格的信息在一个 dict items_by_count

  item_list中的项目:
计数, price = item ['count'],item ['price']
items_by_count [count] ['total_items'] + = 1
items_by_count [count] ['total_price'] + = price

但等待! items_by_count [count] 将抛出 KeyError ,如果 count 不在dict中。这是 defaultdict 。让我们将我们从未见过的 count 的默认值定义为0总价,以及0个总项:

  from collections import defaultdict 
items_by_count = defaultdict(lambda:{
'total_items':0,
'total_price':0
} )

现在我们的代码每次看到都不会抛出异常计数的新值



最后,我们需要实际取平均值。让我们在另一个 dict 中获取我们需要的信息,映射到平均价格。对于词汇理解,这是一个很好的用例:

  {count:item ['total_price'] / item ['total_items'] 
为count,item_by_count.iteritems()中的项

这将遍历 items_by_count dict,并创建我们想要的新dict。 >

将它们放在一起:

 从集合import defaultdict 

def get_average_price(item_list):
items_by_count = defaultdict(lambda:{
'total_items':0,
'total_price':0
})

item_list中的项目:
count,price = item ['count'],item ['price']
items_by_count [count] ['total_items'] + = 1
items_by_count [count] ['total_price'] + = price

return {count:item ['total_price'] / item ['total_items']
用于计数,项目中的项目_by_count.iteritems()}

如果我们传入我们的例子输入dict,这个函数返回:
{3.5:1625,2:1750,3:400}



希望你想要的输出!谨慎的浮动部分在您的特定Python版本。


I have the following list

count = 3.5, price = 2500

count = 3, price = 400

count = 2, price = 3000

count = 3.5, price = 750

count = 2, price = 500

I want to find the average price for all where the count is the same. For example:

count = 2, price = 3000

count = 2, price = 500

3000 + 500 = 3500

3500/2 = 1750

Avg for 'count 2' is 1750

Here's my code so far

avg_list = [value["average"] for value in dictionary_database_list] 

counter_obj = collections.Counter(count_list)

print ("AVG:")

for i in counter_obj:

    print (i, counter_obj[i])

解决方案

I'll admit I'm not 100% clear on what you're looking for here, but I'll give it a shot:

A good strategy when you want to iterate over a list of "things" and accumulate some kind of information about "the same kind of thing" is to use a hash table. In Python, we usually use a dict for algorithms that require a hash table.

To collect enough information to get the average price for each item in your list, we need:

a) the total number of items with a specific "count"

b) the total price of items with a specific "count"

So let's build a data structure that maps a "count" to a dict containing "total items" and "total price" for the item with that "count".

Let's take our input in the format:

item_list = [
    {'count': 3.5, 'price': 2500},
    {'count': 3, 'price': 400},
    {'count': 2, 'price': 3000},
    {'count': 3.5, 'price': 750},
    {'count': 2, 'price': 500},
]

Now let's map the info about "total items" and "total price" in a dict called items_by_count:

for item in item_list:
    count, price = item['count'], item['price']
    items_by_count[count]['total_items'] += 1
    items_by_count[count]['total_price'] += price

But wait! items_by_count[count] will throw a KeyError if count isn't already in the dict. This is a good use case for defaultdict. Let's define the default value of a count we've never seen before as 0 total price, and 0 total items:

from collections import defaultdict
items_by_count = defaultdict(lambda: {
    'total_items': 0,
    'total_price': 0
})

Now our code won't throw an exception every time we see a new value for count.

Finally, we need to actually take the average. Let's get the information we need in another dict, mapping count to average price. This is a good use case for a dict comprehension:

{count: item['total_price'] / item['total_items']
for count, item in items_by_count.iteritems()}

This iterates over the items_by_count dict and creates the new dict that we want.

Putting it all together:

from collections import defaultdict

def get_average_price(item_list):
    items_by_count = defaultdict(lambda: {
        'total_items': 0,
        'total_price': 0
    })

    for item in item_list:
        count, price = item['count'], item['price']
        items_by_count[count]['total_items'] += 1
        items_by_count[count]['total_price'] += price

    return {count: item['total_price'] / item['total_items']
            for count, item in items_by_count.iteritems()}

If we pass in our example input dict, this function returns: {3.5: 1625, 2: 1750, 3: 400}

Which is hopefully the output you want! Be cautious of gotchas like float division in your particular Python version.

这篇关于Python字典 - 从其他值查找平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆