【问题标题】:Learn Python The Hard Way - Exercise 39艰难地学习 Python - 练习 39
【发布时间】:2016-06-28 09:21:21
【问题描述】:

在 Learn Python The Hard Way 的练习 39 中,第 37 到 39 行如下所示:

print "-"*10
for state, abbrev in states.items():
    print "%s has the city %s" % (state, abbrev)

我以为我明白这一点。我以为 Python 是从“states”中获取 KEY:VALUE 并将 KEY 分配给“state”,将 VALUE 分配给“abbrev”。

但是,当我输入以下代码时,我发现发生了一些奇怪的事情:

print "-"*10
for test in states.items():
    print "%s has the city %s" % (test)

它产生与原始代码相同的输出。 但是,它只有在您将%s 两次放入 print 语句时才有效。

有人能解释一下“测试”发生了什么吗? 究竟什么是“测试”?它是一个元组吗? 它似乎包含来自states.items()KEYVALUE

我在这里查看了练习 39 中的其他一些问题,但没有找到相同的查询。

代码如下(适用于 Python 2.7)

# create a mapping of state to abbreviation

states = {
    'Oregan': 'OR',
    'Florida': 'FL',
    'California': 'CA',
    'New York' : 'NY',
    'Michigan' : 'MI'
    }

print "-"*10
for state, abbrev in states.items():
    print "%s has the city %s" % (state, abbrev)

print "-"*10
for test in states.items():
    print "%s has the city %s" % (test)

【问题讨论】:

  • 你不必使用 states.items(),字典的默认可迭代是 key

标签: python python-2.7 dictionary tuples enumeration


【解决方案1】:

您的第一个和第二个代码 sn-p 之间的“缺失环节”解释了为什么它们是等价的:

print "-"*10
for test in states.items():
    state, abbrev = test
    print "%s has the city %s" % (state, abbrev)

【讨论】:

    【解决方案2】:

    states 是一个字典,因此当您调用for test in states.items() 时,它会将字典的每个项目(tuple)分配给test

    然后您只需像使用 for state, abbrev in states.items(): 一样遍历项目并打印它们的键和值

    >>> for state in states.items():
        print (state) # print all the tuples
    
    
    ('California', 'CA')
    ('Oregan', 'OR')
    ('Florida', 'FL')
    ('Michigan', 'MI')
    ('New York', 'NY')
    

    所有详细信息都可以在线获得,例如 Dictionary Iterators 下的PEP 234 -- Iterators

    • 字典实现了一个 tp_iter 槽,它返回一个高效的迭代器,它遍历字典的键。 [...] 这意味着我们可以写

      for k in dict: ... 
      

      相当于,但比

      快得多
      for k in dict.keys(): ... 
      

      只要不违反对字典修改的限制(通过循环或另一个线程)。

    • 将方法添加到显式返回不同类型迭代器的字典中:

      for key in dict.iterkeys(): ...
      
      for value in dict.itervalues(): ...
      
      for key, value in dict.iteritems(): ...
      

      这意味着for x in dictfor x in dict.iterkeys() 的简写。

    【讨论】:

    • 所以如果我理解的话,“test”相当于“for k in dict”,当你用 print 语句迭代时,你必须有两个 %s 实例,因为“ test”既有键又有值?
    • 是的,修饰符 %s 是一个字符串,所以它希望你有 2 个,因为你试图打印一个有键和值的字典条目:)
    • 太好了,非常感谢。起初我尝试了那个“测试”作为打破它的一种方式,然后当它给我这个结果时我感到很惊讶。很好的帮助,谢谢大家!
    猜你喜欢
    • 2015-05-01
    • 2013-04-06
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多