“ Int”对象不可迭代

我正在尝试运行一个for循环。这是我遇到问题的代码部分:

aldurstengd_ororka = {(18, 19, 20, 21, 22, 23, 24):1, (25):0.95, (26):0.90,

(27):0.85, (28, 29):0.75, (30, 31):0.65, (32, 33):0.55, (34, 35):0.45,

(36, 37):0.35, (40, 41, 42, 43, 44, 45):0.15, (46, 47, 48, 49, 50):0.10,

(51, 52, 53, 54, 55):0.075, (56, 57, 58, 59, 60):0.05, (61, 62, 63, 64,

65, 66):0.025}

for age in aldurstengd_ororka.keys():

for item in age:

if ororkualdur == item:

baetur = baetur + ororkulifeyrir * aldurstengd_ororka([age])

因此,我的目的是遍历aldurstengd_ororka,对于字典中的每个“年龄”元组,我为元组中的每个“项目”运行另一个for循环。我得到的错误是

TypeError:“ int”对象不可迭代

回答:

如果aldurstengd_ororka是字典,则此表达式:

aldurstengd_ororka([age])

是一个错误。也许您的意思是:

aldurstengd_ororka[(age)]

编辑:您看到的错误是非常有趣的,我确实使用此代码段重现了它:

for age in aldurstengd_ororka.keys():

print 'age:', age

for item in age:

print item

代码的输出为:

age: (32, 33)

32

33

age: (36, 37)

36

37

age: (51, 52, 53, 54, 55)

51

52

53

54

55

age: (61, 62, 63, 64, 65, 66)

61

62

63

64

65

66

age: (30, 31)

30

31

age: 25

---------------------------------------------------------------------------

TypeError Traceback (most recent call last)

/home/ma/mak/Documents/t.py in <module>()

3 for age in aldurstengd_ororka.keys():

4 print 'age:', age

----> 5 for item in age:

6 print item

7

TypeError: 'int' object is not iterable

因此,发生的事情是Python在将1个元素的元组分配给age变量时对其进行“解包”。因此,年龄(而不是(25)您所期望的)只是25……这有点奇怪。一种解决方法是执行以下操作:

for age in aldurstengd_ororka.keys():

# if not tuple, make it a tuple:

if not type(age) == type( (0,1) ): age = (age,)

print 'age:', age

for item in age:

print item

以上是 “ Int”对象不可迭代 的全部内容, 来源链接: utcz.com/qa/425019.html

回到顶部