作者:VASTEw | 来源:互联网 | 2023-09-25 10:57
Ihavethefollowinglistofdictionarieswhichcontainsthecountryandthevaluesforcorrespondin
I have the following list of dictionaries which contains the country
and the values for corresponding servers.
我有以下字典列表,其中包含国家和相应服务器的值。
[
{'country': 'KR', 'values': ['Server1']},
{'country': 'IE', 'values': ['Server1', 'Server3', 'Server2']},
{'country': 'IE', 'values': ['Server1', 'Server3']},
{'country': 'DE', 'values': ['Server1']},
{'country': 'DE', 'values': ['Server2']},
]
Now I need to calculate the percentage of each server for a particular country. So for instance, for IE
the sum total of both the lists is 5
. Hence the percentage will be calculated as (2/5)*100
for Server1
as there are two Server1
out of five for IE
and similarly for the rest and then add the percentage for Server1
in the dict with percent
as key. So essentially for the above structure the output becomes.
现在我需要计算特定国家/地区的每台服务器的百分比。因此,例如,对于IE,两个列表的总和为5。因此,对于Server1,百分比将被计算为(2/5)* 100,因为IE中有两个Server1,其余的类似于其余,然后在dict中添加Server1的百分比,其中百分比为关键。因此,基本上对于上述结构,输出变为。
[
{"country": "KR", "percent": "100.0000", "values": ["Server1-100.0000"]},
{"country": "IE", "percent": "40.000", "values": ["Server1-40.0", "Server3-40.0", "Server2-20.0"]},
{"country" : "DE", "percent" : "50.0", "values" : ["Server1-50.0", "Server2-50.0"]},
]
I tried the following code.
我尝试了以下代码。
for i in range(len(response) - 1):
for j in range((i+1), len(response) - 1):
if response[i]['country'] == response[j]['country']:
print response[i]['country'], response[j]['country']
total = len(response[i]['values']) + len(response[j]['values'])
print total
for item in response[i]['values']:
for ktem in response[j]['values']:
if item == ktem:
if item == 'Server1':
response[i]['percent'] = 200/total
else:
response[i][percent] = 0
del response[j]
I am stuck to proceed further to get the percentage part correct. Any help?
我坚持继续进一步让百分比部分正确。有帮助吗?
2 个解决方案
I have a more compact method.
我有一个更紧凑的方法。
I think it's more readable and easy to understand. You can refer as below:
我认为它更易读,更容易理解。你可以参考如下:
This is your var I delcare response
:
这是你的var I delcare回复:
respOnse= [
{'country': 'KR', 'values': ['Server1']},
{'country': 'IE', 'values': ['Server1', 'Server3', 'Server2']},
{'country': 'IE', 'values': ['Server1', 'Server3']},
{'country': 'DE', 'values': ['Server1']},
{'country': 'DE', 'values': ['Server2']},
]
Let's merge the values.
让我们合并这些值。
new_res = {}
for e in response:
if e['country'] not in new_res:
new_res[e['country']] = e['values']
else:
new_res[e['country']].extend(e['values'])
You can print new_res
if you want to know its content. It's like as below:
如果您想了解其内容,可以打印new_res。它如下所示:
{
'KR': ['Server1'],
'DE': ['Server1', 'Server2'],
'IE': ['Server1', 'Server3', 'Server2', 'Server1', 'Server3']
}
Invoking collections
module collects elements:
调用集合模块收集元素:
from collections import Counter
new_list = []
for country, values in new_res.items():
# elements are stored as dictionary keys and their counts are stored as dictionary values
merge_values = Counter(values)
# calculate percentage
new_values = []
total = sum(merge_values.values())
for server_name, num in merge_values.items():
#ex: Server1-40.0
new_values.append("{0}-{1:.1f}".format(server_name, num*100/total))
percent = merge_values["Server1"]*1.0*100/total
new_list.append({"country": country,
"percent": percent,
"values": new_values})
You can print new_list
when finishing calculating result:
完成计算结果后可以打印new_list:
[{'country': 'KR', 'percent': 100.0, 'values': ['Server1-100.0']},
{'country': 'DE', 'percent': 50.0, 'values': ['Server1-50.0', 'Server2-50.0']},
{'country': 'IE', 'percent': 40.0, 'values': ['Server1-40.0', 'Server2-20.0', 'Server3-40.0']}]
So you can get answer you want.
所以你可以得到你想要的答案。
Let's say you have
让我们说你有
orig = [
{'country': 'KR', 'values': ['Server1']},
{'country': 'IE', 'values': ['Server1', 'Server3', 'Server2']},
{'country': 'IE', 'values': ['Server1', 'Server3']},
{'country': 'DE', 'values': ['Server1']},
{'country': 'DE', 'values': ['Server2']},
]
You can create a new dictionary that has a list of what servers are in what countries and their counts
您可以创建一个新字典,其中列出了哪些服务器位于哪些国家/地区及其计数
newDict = {}
for c in orig:
if c['country'] not in newDict:
newDict[c['country']] = dict()
for s in c['values']:
if s in newDict[c['country']]:
newDict[c['country']][s] = newDict[c['country']][s] + 1
else:
newDict[c['country']][s] = 1
which will be of the form:
其形式如下:
{'KR': {'Server1': 1},
'DE': {'Server1': 1, 'Server2': 1},
'IE': {'Server1': 2, 'Server2': 1, 'Server3': 2}}
You can then calculate the percentages as such:
然后,您可以计算百分比:
output = []
for country in newList:
total = 0
for server in newList[country]:
total = total + newList[country][server]
output.append({"country": country, "percent": (100.0 * newList[country]['Server1'])/total})
which will produce
这将产生
[{'country': 'KR', 'percent': 100.0},
{'country': 'DE', 'percent': 50.0},
{'country': 'IE', 'percent': 40.0}]
I'll leave it as an exercise for the reader to optimize and add the other fields that you want
我将把它作为练习让读者优化并添加你想要的其他字段