gpt4 book ai didi

python - "Int"对象不可迭代

转载 作者:行者123 更新时间:2023-11-28 20:47:51 25 4
gpt4 key购买 nike

我正在尝试运行 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

因此,当将 1 个元素的元组分配给 age 变量时,Python 会“解包”该元组。所以 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

关于python - "Int"对象不可迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17999752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com