两者之间不会有太大的速度差异。您正在迭代两个序列,只有这些结构的确切数据类型不同。
通过使用以下方法,您的dictionary
循环可能会更加高效:.iteritems()
dictionary = {'North': 'N', 'South': 'S', 'East': 'E', 'West': 'W'}
address = 'North South East West'
for key, value in dictionary.iteritems():
address = address.replace(key, value)
由于.iteritems()
为您提供了可迭代的(key, value)
对,因此此方法与使用元组完全相同。
使用timeit
module,您可以看到两种方法之间没有真正的区别:
>>> import timeit
>>> def dictionary(address, d={'North': 'N', 'South': 'S', 'East': 'E', 'West': 'W'}):
... for s, repl in d.iteritems():
... address = address.replace(s, repl)
...
>>> def tuples(address, t=[('North', 'N'), ('South', 'S'), ('East', 'E'), ('West', 'W')]):
... for s, repl in t:
... address = address.replace(s, repl)
...
>>> timeit.timeit("test('North South East West')", 'from __main__ import dictionary as test')
2.5873939990997314
>>> timeit.timeit("test('North South East West')", 'from __main__ import tuples as test')
2.5879111289978027