【问题标题】:List assignment out of index列出索引外的分配
【发布时间】:2011-11-01 03:16:30
【问题描述】:

我有以下程序将字典键分配给数组(addr[])并将值分配给相应的数组(msg[]

import smtplib  

class item:
    id = 0 # next available Item ID
    def __init__(self,startBid,desc):
        self.id = item.id
        item.id += 1
        self.highBid = startBid
        self.highBidder = None
        self.desc = desc
        self.isopen = True

item1 = item(200.30, "bike with a flat tire")
item2 = item(10.4, "toaster that is very large")
item3 = item(40.50, "computer with 8 gb of ram")

clnts = {'test@hotmail.com':[item1,item3], 'test@yahoo.com':[item2] }

def even(num):
    if (num % 2 == 0):
        return True
    else:
        return False

def getmsg(clnts):
    index = 0
    j = 0
    msg = []
    addr = []

    for key in clnts:
        addr[j] = key
        for key in values:
            msg[j] += str(key.highbidder()) + key.highbid()
            index += 1
            j += 1

getmsg(clnts)

我已经尝试并尝试解决此问题,但我不断收到错误消息:

line 39, in getmsg
    addr[j] = key
IndexError: list assignment index out of range

【问题讨论】:

    标签: python indexing


    【解决方案1】:

    在 Python 中,不能分配给不存在的索引:

    >>> x = []
    >>> x[0] = True
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    IndexError: list assignment index out of range
    

    代替

    addr[j] = key
    

    试试

    addr.append(key)
    

    你可以完全取消j,因为你必须对msg做同样的事情。

    您的代码还有一些其他问题不属于您的问题;我假设这些只是试图为一个问题做一个简单的例子时的错误。

    【讨论】:

    • 好答案。 list.append() 是常用的 Python 方法。
    【解决方案2】:

    addr = [] 创建一个没有元素的空列表。所以 addr[0] 不存在,并且尝试将任何内容存储到不存在的位置将生成 IndexError。请改用addr.append(key)

    或者,您可以使用更多 Pythonic 技术一次性创建和初始化列表,而不是使用索引 j 的 FORTRAN 样式循环:

    addr = list(clnts.keys())
    

    【讨论】:

      【解决方案3】:

      使用list.append()

      def getmsg(clnts):
      
          msg = []
          addr = []
      
          for key in clnts:
              addr.append(key)
      
              for key in values:
                  msg.append(str(key.highbidder()) + key.highbid())
      

      如果你有勇气,试试list comprehensions


      不过,您很快就会发现另一个问题:

      NameError: global name 'values' is not defined
      

      我猜你想要 clnts 中每个 key 对应的值:

      def getmsg(clnts):
      
          msg = []
          addr = []
      
          for key in clnts:
              addr.append(key)
      
              for value in clnts[key]:
                  msg.append(str(value.highbidder()) + value.highbid()) 
      

      之后你会发现另一个问题:

      AttributeError: item instance has no attribute 'highbidder'
      

      我会让你从那里拿走。

      【讨论】:

      猜你喜欢
      • 2021-11-23
      • 2020-02-03
      • 1970-01-01
      • 2013-05-31
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多