gpt4 book ai didi

Python - 类型错误 : 'int' object has no attribute '__getitem__'

转载 作者:太空宇宙 更新时间:2023-11-04 03:53:19 25 4
gpt4 key购买 nike

我是 Python 初学者,在列表中迭代时遇到问题。这是我遇到问题的一段代码:

for x in list(xrange(instance.nbw)):
sddpbw.append(choice(sddpfw))
print sddpbw

for t in reversed(list(xrange(instance.T))):

if t>0:
for u in sddpbw:
# for n in list(xrange(1,instance.NUMPATHS+1,passo)):
for n in pairs[t][u-1]:
if n != u:
for p in instance.HP:
x[n-1][t-1][p-1]=x[u-1][t-1][p-1]

我有一个以前的列表 (sddpfw),想从中选择一些元素并创建另一个列表 (sddpbw)。导出是:

[4, 2]
Traceback (most recent call last):
File "PDDE.py", line 179, in <module>
x[n-1][t-1][p-1]=x[u-1][t-1][p-1]
TypeError: 'int' object has no attribute '__getitem__'

但是如果我评论创建变量 sddpbw 的部分并手动创建它,它工作正常:

# for x in list(xrange(instance.nbw)):
# sddpbw.append(choice(sddpfw))
sddpbw=[4, 2]
print sddpbw

我不明白为什么会这样。

最佳答案

您在此行重置了您的 x 变量。循环结束后,您会得到 x 作为某个整数。

for x in list(xrange(instance.nbw)):
sddpbw.append(choice(sddpfw))

例如

>>> c = [1,2,3]
>>> c
[1, 2, 3]
>>> for c in xrange(1, 3):
... print(c)
...
1
2
>>> c
2

您需要将此 x 更改为任何其他名称。

for _ in list(xrange(instance.nbw)):
sddpbw.append(choice(sddpfw))

关于Python - 类型错误 : 'int' object has no attribute '__getitem__' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20104293/

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