AttributeError:'str'对象在循环

时间:2015-12-21 19:21:10

标签: python python-2.7

def printdash():
    print('-' * 10)


# creates a mapping of state to abbreviation
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}

# creates a basic set of states with some cities in them

cities = {
'CA': 'Sacramento',
'MI': 'Lansing', 
'FL': 'Tallahasee'}

# add some more cities to the list
cities['NY'] = 'Albany'
cities['OR'] = 'Eugene'

# Print out some cities
printdash()
print('New York State has: ', cities['NY'])
print('Oregon has: ', cities['OR'])

# print some states
printdash()
print 'Michigan\'s abbreviation is: ' , states['Michigan']
print 'Florida\'s abbreviation is: ', states['Florida']

# do it by using the state then cities dict. Nested dicts!
printdash()
print 'Michigan has: ', cities[states['Michigan']]
print 'Florifa has: ', cities[states['Florida']] 

# print every states abbreviation
printdash()
for states, abbrev in states.items():
    print '%s is abbreviated as %s' % (states, abbrev)
# end

# print every city in each state
printdash()
for abbrev, cities in cities.items():
    print '%s has the city %s' % (abbrev, cities)
# end

# doing both at the same time
printdash()
for state, abbrev in states.items():
    print '%s state is abbreviated %s and has city %s' % (state, abbrev,  cities[abbrev])

每次运行它都会到达第54行(最后一个for循环),然后引发属性错误标志。对于我的生活,我无法弄清楚我做错了什么作为另外两个循环,在大多数相同的时尚工作中没有问题。

在这个网站上查找其他解决方案,我发现这些例子比我能理解的要复杂得多,而且解决方案似乎比这个非常普遍的情况更具体。

克斯!

3 个答案:

答案 0 :(得分:2)

当您在第一个循环中指定states作为目标时,您会将states的名称重新指定给states.items()元组的第一个项目。

这是您正在做的简化版本:

>>> i = "hello"
>>> for i in range(2): print i
... 
0
1
>>> i
1

如您所见,i是循环后的int而非str,其引用的值已更改

作为解决方案,只需将循环中的states重命名为其他内容,例如statetmp_states。所以:

for state, abbrev in states.items():
    print '%s is abbreviated as %s' % (state, abbrev)

另外对存在相同模式的其他循环执行相同操作,例如for abbrev, cities in cities.items(): - > for abbrev, city in cities.items()

答案 1 :(得分:1)

该行

for states, abbrev in states.items():
    print('%s is abbreviated as %s' % (states, abbrev))

造成麻烦。

由于python中循环变量的范围不仅限于循环(你可以说,它们会泄漏到你的程序中),所以此行states之后将是一个字符串。< / p>

您可以通过运行

来调试它
print(states)
for states, abbrev in states.items():
    print('%s is abbreviated as %s' % (states, abbrev))
print(states)

将打印

----------
{'California': 'CA', 'Michigan': 'MI', 'New York': 'NY', 'Florida': 'FL', 'Oregon': 'OR'}
California is abbreviated as CA
Michigan is abbreviated as MI
New York is abbreviated as NY
Florida is abbreviated as FL
Oregon is abbreviated as OR
Oregon

此外,您应该检查您对print的使用情况。请坚持使用一个版本的print语句,print 'foo' print('foo')。第二种用法(作为函数)是唯一可以在Python 3.X中使用的用法。

答案 2 :(得分:1)

'city'和'states'都被第一个和第二个for循环覆盖。使用不同的变量名称应该修复它。