这条线单独工作很好,但在for循环中不工作

2024-06-24 11:56:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图形成一个集合字典,但我的代码似乎在for循环之外工作,但在它里面失败了。你知道吗

谢谢你的帮助

for n in xrange(tc):
    truckgoals[n]= set()

#this works fine    
truckgoals[0].add(packages[0]["target"])

for sol in feas:
    print "for solutions" + str(sol)
    for c in xrange(pcount):
        print int(sol[c])
        # this fails
        truckgoals[int(sol[c])].add(packages[c]["target"])
    for tur in xrange(tc):
        print "goals of truck " +str(tur) + " is " + str(truckgoals[tur]) 
    print "next"
    truckgoals = [0] * tc
    pass

错误:

...
for solutions(0, 2, 2, 3, 3, 4)
0
Traceback (most recent call last):
  File "/home/mbp/workspace/Case Study/main.py", line 103, in <module>
    truckgoals[int(sol[c])].add(packages[c]["target"])
AttributeError: 'int' object has no attribute 'add'

Tags: inaddtargetforpackagesthisinttc
1条回答
网友
1楼 · 发布于 2024-06-24 11:56:11

在循环中用列表替换了truckgoals

truckgoals = [0] * tc

这将创建一个长度为tc的整数列表。你知道吗

因为您正在使用xrange()为字典生成键,所以在我看来,不管怎样,使用集合列表而不是字典都是一个更好的选择。你知道吗

相关问题 更多 >