Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的字典和访问它的不同方式_Python_Dictionary - Fatal编程技术网

Python中的字典和访问它的不同方式

Python中的字典和访问它的不同方式,python,dictionary,Python,Dictionary,就速度和编写Python代码而言,哪种方法是访问Python词典的最佳方法?由于两者都返回相同的结果,我更喜欢第二种方法,因为它更直观 for name, number in phonebook.iteritems(): print "Phone number of %s is %d" % (name, number) 或 这可能是非常主观的(两个示例的计时显示执行速度没有差异),但是如果您要访问字典的每个值,我更喜欢第一种方法 如果您只想访问某些值,那么我建议使用第二种方法。例如:

就速度和编写Python代码而言,哪种方法是访问Python词典的最佳方法?由于两者都返回相同的结果,我更喜欢第二种方法,因为它更直观

for name, number in phonebook.iteritems():
    print "Phone number of %s is %d" % (name, number)


这可能是非常主观的(两个示例的计时显示执行速度没有差异),但是如果您要访问字典的每个值,我更喜欢第一种方法

如果您只想访问某些值,那么我建议使用第二种方法。例如:

for key in phonebook:
    if key.startswith("Sm"):
        print "Phone number of %s is %d" % (key, phonebook[key]) 

我认为这真的只是个人喜好。我所知道的这两种语言在性能、内存使用等方面并没有什么真正的区别。不管你想用哪种方式,我都觉得这个问题很有趣(因为我一直想知道自己应该用哪种习惯用语)。不过,我同意,一个关于“最佳”方式的问题太不具体了——最佳方式是什么?可读性、速度、内存使用、Pythonicity…?@TimPietzcker感谢Tim,我说的最好的方式是速度和‘Pythonicity’。我厌倦了Stack Exchange的下载业务,问答论坛毫无建设性,到处都是势利小人,他们认为自己知道的太多了,甚至在投票否决帖子之前都不会发表评论。我不知道互相帮助的感觉发生了什么,因为我们都在这里学习。希望看到一个没有否决权的问答论坛!
for key in phonebook:
    if key.startswith("Sm"):
        print "Phone number of %s is %d" % (key, phonebook[key])