目录
1. print( 坑的信息 )
- 挖坑时间:2019/01/19
- 明细
坑的编码 | 内容 |
---|---|
Py016-1 | 字典的遍历在 Python2 与 Python3 中区别 |
2. 开始填坑
(1) Python2 中字典的遍历
#例1 Python2 中字典的遍历
dict1 = {"a":"apple", "b":"banana", "c":"cherry", "d":"durian"}
for k in dcit1:
print "dict[% s] =" % k, dict1[k]
>>>
dict1[a] = apple
dict1[b] = banana
dict1[c] = cherry
dict1[d] = durian
# 例2 Python2 字典对 items() 的使用
# iterms() 把字典中每队 key 和 value 组成了一个元组,并把这些元组存放到列表中返回
dict2 = {"a":"apple", "b":"banana", "c":"cherry", "d":"durian"}
print dict2.items()
>>>
[('a', 'apple'), ('c', 'cherry'), ('b', 'banana'), ('d', 'durian')]
# 例3 Python2 使用字典的 items() 方法实现字典的遍历
dict3 = {"a":"apple", "b":"banana", "c":"cherry", "d":"durian"}
for (k, v) in dict3.items():
print "dict3[% s] =" % k, v
>>>
dict3[a] = apple
dict3[b] = banana
dict3[d] = durian
dict3[c] = cherry
# 例4 Python2 使用 iteritems()、iterkeys()、itervalues() 实现字典的遍历
dict4 = {"a":"apple", "b":"banana", "c":"cherry", "d":"durian"}
print dict4.iteritems() # 返回字典的遍历器对象
for k, v in dict4.iteritems():
print "dict4[% s] =" % k, v # k、v 与遍历器对象指定的元组 (key, value) 对应
for (k, v) in zip(dict4.iterkeys(), dict4.itervalues()):
print "* dict4[% s] =" % k, v # k 与 iterkeys() 指向的 key 列表中的值对应
# v 与 itervalues() 指向的 value 列表中的值对应
>>>
<dictionary-itemiterator object at 0x00A50B60>
dict4[a] = apple
dict4[b] = banana
dict4[d] = durian
dict4[c] = cherry
* dict4[a] = apple
* dict4[b] = banana
* dict4[d] = durian
* dict4[c] = cherry
(2) Python3 中字典的遍历
# 例5 Python3 中字典的遍历
dict5 = {"a":"apple", "b":"banana", "c":"cherry", "d":"durian"}
for k in dict5:
print("dict5[{0}] = {1}".format(k, dict5[k]))
>>>
dict5[a] = apple
dict5[b] = banana
dict5[c] = cherry
dict5[d] = durian
# 例6 Python3 使用 items()、keys()、values() 实现字典的遍历
dict6 = {"a":"apple", "b":"banana", "c":"cherry", "d":"durian"}
for k, v in dict6.items():
print("dict6[{0}] = {1}".format(k, v))
for k in dict6.keys():
print("* dict6[{0}] = {1}".format(k, dict6[k]))
for v in dict6.values(): # 只访问字典的值
print(v)
>>>
dict6[a] = apple
dict6[b] = banana
dict6[c] = cherry
dict6[d] = durian
* dict6[a] = apple
* dict6[b] = banana
* dict6[c] = cherry
* dict6[d] = durian
apple
banana
cherry
durian
(3) 结论
- Python2/3 中的字典都是无序的,且 Python2 输出字典中的键值对时是随机的,但Python3 输出字典中的键值对时会按一定顺序
- 由于 print 在 Python2 与 Python3 中使用方式不同,导致其遍历时受影响
- Python2 使用 iteritems()、iterkeys()、itervalues() 方法;Python3 使用 items()、keys()、values() 方法
- Python2 中的 iteritems() 与 Python3 中的 items() 类似;而 iterkeys() 与 keys()、itervalues() 与 values() 差别较大。(具体观察 例4 与例6)
不足之处,还请诸位多多指教!