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
395 views
in Technique[技术] by (71.8m points)

python - "Int" object is not iterable

I'm trying to run a for loop. Here's the section of my code I'm having trouble with:

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])

So my intention is to run through aldurstengd_ororka, and for each "age" tuple in the dictionary, I run another for loop for each "item" inside the tuple. The error I get is

TypeError: 'int' object is not iterable

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

If aldurstengd_ororka is a dictionary, then this expression:

aldurstengd_ororka([age])

is an error. Perhaps you meant something like:

aldurstengd_ororka[(age)]

EDIT: The error you were seeing is quite interesting, I did reproduce it with this snippet:

for age in aldurstengd_ororka.keys():
    print 'age:', age 
    for item in age:
        print item

The output of the code is:

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

So, what happens is Python 'unpacks' a tuple of 1 element when assigning it to the age variable. So age instead of (25), as you would expect, is just 25... It's a bit strange. A workaround would be to do something like:

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

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

...