I'm a beginner in python and i'm having trouble with iterating in a list. This is the piece of code I'm having trouble with:
我是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]
I have a previous list (sddpfw) and want to chosse some elements from it and create another list (sddpbw). The exit is:
我有一个以前的列表(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__'
But if I comment the section that creates the variable sddpbw and create it mannually it works fine:
但是,如果我对创建变量sddpbw的部分进行注释并创建它,它就会正常工作:
# for x in list(xrange(instance.nbw)):
# sddpbw.append(choice(sddpfw))
sddpbw=[4, 2]
print sddpbw
I can´t figure out why this is happening.
我可以´t弄清楚这是为什么。
1 个解决方案
#1
2
Your reset your x
variable on this lines. When loop finished, you get x
as some integer number.
在这一行重新设置x变量。当循环结束时,将得到x作为一个整数。
for x in list(xrange(instance.nbw)):
sddpbw.append(choice(sddpfw))
For example
例如
>>> c = [1,2,3]
>>> c
[1, 2, 3]
>>> for c in xrange(1, 3):
... print(c)
...
1
2
>>> c
2
You need change this x
to anything else name.
您需要将这个xto更改为其他名称。
for _ in list(xrange(instance.nbw)):
sddpbw.append(choice(sddpfw))
#1
2
Your reset your x
variable on this lines. When loop finished, you get x
as some integer number.
在这一行重新设置x变量。当循环结束时,将得到x作为一个整数。
for x in list(xrange(instance.nbw)):
sddpbw.append(choice(sddpfw))
For example
例如
>>> c = [1,2,3]
>>> c
[1, 2, 3]
>>> for c in xrange(1, 3):
... print(c)
...
1
2
>>> c
2
You need change this x
to anything else name.
您需要将这个xto更改为其他名称。
for _ in list(xrange(instance.nbw)):
sddpbw.append(choice(sddpfw))