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

2024-04-24 20:23:04 发布

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

我不确定为什么我会把这个列表索引超出界限错误

基本上,应该发生的是,我发送一个twitter用户ID列表,然后将它们分成100个块,在twitter中查找它们,然后使用userid作为键将它们添加到字典中。那么假设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

错误如下:

^{pr2}$

Tags: oftheinloop列表fordictionarycount
3条回答

toGet初始化为空列表,您正试图为[0]赋值。这是违法的。改用追加:

toGet.append(lookupIds[count])
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

这很可能是因为您试图在索引0不存在时查找它。示例:

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

相关问题 更多 >