0

嘿,这是我在这里的第二篇文章,我只是 python 的新手,而我在 Uni 学习。这是从我的第一个问题“自动调用字典中的键”开始的。

所以我最初在同一个 for 循环中进行了所有设置,但是,我得到了错误

The error was:__setitem__
Attribute not found.
You are trying to access a part of the object that doesn't exist.

我对字典和键有错误的想法吗?我认为如果 pictureCount=3 它将通过 for 语句运行 3 次并创建图片 [1]、图片 [2] 和图片 [3] 变量。它似乎正在经历第一个循环,但是一旦进入图片[2],就会发生错误。我的思路是,没有图片[2],它唯一创建的图片[1] 一遍又一遍。如果您需要更多代码,请告诉我。

      for p in range(1,pictureCount+1):
        picture[p]=makePicture(pickAFile())

      for p in range(1,pictureCount+1):
        width[p]=getWidth(picture[p])
         height[p]=getHeight(picture[p])
         totalWidth=totalWidth+width[p]
         height=getHeight(picture[p])
         if height > totalHeight:
           totalHeight=height

好的,这是完整的代码。

    def comicStrip():
      picture={}
      width={}
      height={}
      totalWidth=0
      totalHeight=0
      pixelCount=0
      loopCounter=0
      pictureCount=requestInteger("How many pictures do you want in the comic strip?(1-4)")
      while pictureCount <1 or pictureCount >4:     
        pictureCount=requestInteger("How many pictures do you want in the comic strip?(1-4)")

      for p in range(1,pictureCount+1):
        picture[p]=makePicture(pickAFile())

      for p in range(1,pictureCount+1):
        width[p]=getWidth(picture[p])
        height[p]=getHeight(picture[p])
        totalWidth=totalWidth+width[p]
        height=getHeight(picture[p])
        if height > totalHeight:
          totalHeight=height
      cStrip=makeEmptyPicture(totalWidth, totalHeight)
      pixelCount=0

      while loopCounter < pictureCount:
        sourceX=0
        for targetX in range(pixelCount,width[p]):
          sourceY=0
          for targetY in range(0,height[p]):
            color = getColor(getPixel(picture[1],sourceX,sourceY))
            setColor(getPixel(cStrip,targetX,targetY),color)
            sourceY=sourceY+1
            pixelCount=pixelCount+1
          sourceX=sourceX+1
        addRectFilled(cStrip,0,0,p1Width,20,white)
        addRect(cStrip,0,0,p1Width,20)
        addRect(cStrip,0,0,p1Width,p1Height)
        caption=requestString("Enter the caption for this picture.") 
        addText(cStrip,1,19,str(caption))
        loopCounter=loopCounter+1

我很确定间距是正确的,我必须在复制和粘贴后重新调整。

4

1 回答 1

0

代码中的错误不在线

height[p]=getHeight(picture[p])

它在下面 2 行

height=getHeight(picture[p])

此行应替换为以下内容

totalHeight = getHeight(picture[p]).

我不是 python 专家,但在 for 循环的第一次迭代之后,解释器似乎将高度从数组(或 dict)变为普通变量。在第二次迭代行height[p]=getHeight(picture[p])尝试访问元素p但不再存在。

我尝试了以下代码 JES 并得到了同样的错误

array1 ={}
array1[1] = 5
array1 = 7
array1[1] = 8

print array1[1]
于 2014-02-27T08:41:11.980 回答