在for循环中,键似乎不“计数”

2024-03-28 10:45:53 发布

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

嘿,这是我在这里的第二篇文章,我只是python的新手,而我在Uni学习。我的第一个问题是“自动从dict调用键”。你知道吗

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

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

我对dict和keys有错误的看法吗?我认为如果pictureCount=3,它将在for语句中运行3次,并创建picture[1]、picture[2]和picture[3]变量。它似乎正在经历第一个循环,但一旦到达picture[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

我敢肯定,间距是正确的,我必须重新调整后,复制和粘贴。你知道吗


Tags: theinforrangewidthheightpicturepixelcount
1条回答
网友
1楼 · 发布于 2024-03-28 10:45:53

代码中的错误不在线

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

在下面两行

height=getHeight(picture[p])

该行应替换为以下内容

totalHeight = getHeight(picture[p]).

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

我尝试了下面的代码,得到了相同的错误

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

print array1[1]

相关问题 更多 >