if语句中的Python列表索引错误

时间:2014-06-17 01:36:41

标签: python list dictionary

我不知道为什么我得到这个列表索引越界错误

基本上应该发生的是我发送我的def一个twitter userIds列表,然后将它们分成100个块,在twitter中查找它们,然后使用userIds作为键将它们添加到字典中。所以让我们说00001是约翰尼,我们查找00001得到约翰尼,然后用00001,约翰尼做一本字典。然而if语句似乎不会触发。

以下是代码:

 def getUserName(lookupIds):
     l = len(lookupIds) # length of list to process
     i = 0 #setting up increment for while loop 
     screenNames = {}#output dictionary
     count = 0 #count of total numbers processed
     print lookupIds
     while i < l:
         toGet = []
         if l - count > 100:#blocks off in chunks of 100
             for m  in range (0,100):
                toGet[m] = lookupIds[count]
                count = count + 1
                print toGet
         else:#handles the remainder 
              r = l - count 
              print screenNames
              for k  in range (0,r):#takes the remainder of the numbers 
                  toGet[k] = lookupIds[count]
                  count = count + 1
              i = l   # kills loop

          screenNames.update(zip(toGet, api.lookup_users(user_ids=toGet)))
          #creates a dictionary screenNames{user_Ids, screen_Names}

     #This logic structure breaks up the list of numbers in chunks of 100 or their
     #Remainder and addes them into a dictionary with their userID number as the 
     #index value Count is for monitoring how far the loop has been progressing.    
     print len(screenNames) + 'screen names correlated'
     return screenNames

错误如下:

Traceback (most recent call last):
  File "twitterBot2.py", line 78, in <module>
    toPrint = getUserName(followingids)#Testing Only
  File "twitterBot2.py", line 42, in getUserName
    toGet[k] = lookupIds[count]
IndexError: list assignment index out of range

3 个答案:

答案 0 :(得分:1)

toGet初始化为空列表,并且您尝试为[0]赋值。这是非法的。请改为使用附加:

toGet.append(lookupIds[count])

答案 1 :(得分:0)

这很可能是因为当它不存在时,你试图查找索引零。例如:

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

答案 2 :(得分:0)

def getUserName(lookUpIds):
    blockSize = 100
    screenNames = {}
    indexes = xrange(0, len(lookUpIds), blockSize)
    blocks = [lookUpIds[i:(i + blockSize)] for i in indexes]
    for block in blocks:
        users = api.lookup_users(user_ids=block)
        screenNames.update(zip(block, users))

    return screenNames