Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

关于python遍历字典基础

for key in dictfor key in dict.keys() 它们有什么不一样吗?我看教程好像除了第二种多了 .keys() ,好像没有区别啊?

x = {'a':'A', 'b':'B'} 
for key in x: 
    print(key)
a
b
x = {'a':'A', 'b':'B'} 
for key in x.keys(): 
    print(key)
a
b

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

for key in x 要比 for key in x.keys()快 毕竟少调用了一个函数
keys/values/items是dict的三种视图,对应不同的dictiter,适合传递给其他函数遍历
同样要获得dictiter_key x.__iter__() 要比 x.keys()__iter__() 更直接


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...