函数的返回未达到预期。你知道吗
我的环境py2.7.11 centos6.5。你知道吗
我希望函数返回这样的返回
{'www.baidu.com': {'3xx': 0, 'response_time': 0.126, '5xx': 0, '4xx': 1},
'www.google.com': {'3xx': 0, 'response_time': 0, '5xx': 0, '4xx': 0}}
但事实上是这样的回报。不应分配send_dict['www.google.com']['response_time']
和send_dict['www.google.com']['response_code']
。但为什么呢?你知道吗
{'www.baidu.com': {'3xx': 0, 'response_time': 0.126, '5xx': 0, '4xx': 1},
'www.google.com': {'3xx': 0, 'response_time': 0.126, '5xx': 0, '4xx': 1}}
Python代码:
#!/usr/bin/python
# -*- coding: utf-8 -*-
sink_dict = {'sink_zabbix_monitor_keys': '3xx,4xx,5xx,response_time',
'sink_zabbix_domain_keys': 'www.baidu.com,www.google.com'}
sub_send_dict = dict.fromkeys(sink_dict['sink_zabbix_monitor_keys'].split(','), 0)
send_dict = dict.fromkeys(sink_dict['sink_zabbix_domain_keys'].split(','), sub_send_dict)
def calculate_item(item):
response_code_dict = dict.fromkeys(sink_dict['sink_zabbix_domain_keys'].split(','), 0)
response_time_dict = dict.fromkeys(sink_dict['sink_zabbix_domain_keys'].split(','), 0)
domain = item['domain']
response_code_dict[domain] = int(item['response_code'])
response_time_dict[domain] = float(item['response_time'])
if domain in send_dict:
print domain
if response_time_dict[domain] > float(send_dict[domain]['response_time']):
send_dict[domain]['response_time'] = response_time_dict[domain]
send_dict[domain][str(response_code_dict[domain])[0] + "xx"] += 1
return send_dict
tmp_item = {'domain': 'www.baidu.com', 'response_time': '0.126', 'response_code': '401'}
tmp_item1 = {'domain': 'www.google.com', 'response_time': '0.126', 'response_code': '401'}
tmp_item2 = {'domain': 'www.baidu.com', 'response_time': '0.166', 'response_code': '401'}
print calculate_item(tmp_item)
给你:
这叫做听写理解。这是因为我将字典的shallow copy分配给键。
dict.fromkeys()
将值赋给每个键,所有键将共享相同的sub_send_dict
引用。你知道吗从(链接的)python文档:
相关问题 更多 >
编程相关推荐