Python 字典的遍历
程序员文章站
2024-01-23 18:08:40
...
# encoding: utf-8
test_dict = {
'attack': 379,
'attack_growth': 16.8,
'bp_size': 80,
'critical_rate': 0.15,
'ctype': '2',
'defense': 155,
'defense_growth': 8.25,
'exp_type': 'c',
'fate_id': ['ch_10004', 'ch_10005', 'ch_10006', 'ch_20003', 'ch_20004'],
'hp': 1861,
'hp_growth': 69.6,
'max_talent_lv': 7,
'name': 'caocao',
'pvp_skill_rate': 1,
'recover': 281,
'recover_growth': 11.8,
'souls_needed': 30,
'star': '5',
'talent_lv': 0,
'who_is': 'caocao',
}
# 不同的遍历方法
def test1():
for key in test_dict: # 这种最快, 其实也很显而易见
pass
def test2():
for key in test_dict.keys():
pass
def test3():
for key, value in test_dict.items():
pass
if __name__ == '__main__':
from timeit import Timer
t1 = Timer("test1()", "from __main__ import test1")
t2 = Timer("test2()", "from __main__ import test2")
t3 = Timer("test3()", "from __main__ import test3")
# 执行100,000次的时间
print t1.timeit(100000)
print t2.timeit(100000)
print t3.timeit(100000)
# 3次执行100,000次的时间
print t1.repeat(3, 100000)
print t2.repeat(3, 100000)
print t3.repeat(3, 100000)
结果:
0.0656280517578
0.0932841300964
0.217456817627
[0.06363296508789062, 0.062133073806762695, 0.0649728775024414]
[0.08316302299499512, 0.08275103569030762, 0.08605194091796875]
[0.21467804908752441, 0.19786405563354492, 0.20139288902282715]
但空的循环没有意义
# encoding: utf-8
test_dict = {
'attack': 379,
'attack_growth': 16.8,
'bp_size': 80,
'critical_rate': 0.15,
'ctype': '2',
'defense': 155,
'defense_growth': 8.25,
'exp_type': 'c',
'fate_id': ['ch_10004', 'ch_10005', 'ch_10006', 'ch_20003', 'ch_20004'],
'hp': 1861,
'hp_growth': 69.6,
'max_talent_lv': 7,
'name': 'caocao',
'pvp_skill_rate': 1,
'recover': 281,
'recover_growth': 11.8,
'souls_needed': 30,
'star': '5',
'talent_lv': 0,
'who_is': 'caocao',
}
# 不同的遍历方法
def test1():
data = {}
for key in test_dict:
data[key] = test_dict[key]
return data
def test2():
data = {}
for key in test_dict.keys():
data[key] = test_dict[key]
return data
def test3():
data = {}
for key, value in test_dict.items():
data[key] = value
return data
print test1()
print test2()
print test3()
if __name__ == '__main__':
from timeit import Timer
t1 = Timer("test1()", "from __main__ import test1")
t2 = Timer("test2()", "from __main__ import test2")
t3 = Timer("test3()", "from __main__ import test3")
# 执行100,000次的时间
print t1.timeit(100000)
print t2.timeit(100000)
print t3.timeit(100000)
# 3次执行100,000次的时间
print t1.repeat(3, 100000)
print t2.repeat(3, 100000)
print t3.repeat(3, 100000)
结果:
0.39611697197
0.423596143723
0.477458953857
[0.41298508644104004, 0.3765869140625, 0.3731379508972168]
[0.4185318946838379, 0.42104601860046387, 0.4249718189239502]
[0.42894506454467773, 0.4049968719482422, 0.3907771110534668]
差别没那么明显, 不同的遍历在不同地方处理数据
上一篇: R语言箱线图创建实例讲解