IndexError: list index out of range in loop

IndexError: list index out of range in loop

我正在使用 Python 3 / Tweepy 创建一个列表,其中包含与各种 Twitter 用户名关联的用户名。

我的代码创建一个空字典,遍历列表中的句柄以获取用户名,将此信息保存在字典中,然后将字典附加到新列表。

当我 运行 代码时,我得到 IndexError: list index out of range。当我删除 for 循环的第 4 行时,我没有收到错误。关于如何解决该问题的任何想法?为什么这行代码会导致错误?谢谢!

这是我的代码:

def analyzer():
handles = ['@Nasdaq', '@Apple', '@Microsoft', '@amazon', '@Google', '@facebook', '@GileadSciences', '@intel']
data = []
# Grab twitter handles and append the name to data
for handle in handles:
    data_dict = {}
    tweets = api.user_timeline(handle)
    data_dict['Handle'] = handle
    data_dict['Name'] = tweets[0]['user']['name']
    data.append(data_dict)

我猜主要问题在下面的代码中

 tweets = api.user_timeline(handle)

api.user_timeline() 可能 returns 您清空列表并且您正在尝试访问 此空列表中的第一个元素。

 tweets[0]

这就是您遇到 'index out of range' 问题的原因。

您可以像这样修改您的代码 -

for handle in handles:
    data_dict = {}
    tweets = api.user_timeline(handle)
    data_dict['Handle'] = handle
    if tweets:
        data_dict['Name'] = tweets[0]['user']['name']
    data.append(data_dict)

由于您尝试使用索引 0 访问的空列表而发生错误。您可以通过检查列表是否为空来控制此错误:

def analyzer():
handles = ['@Nasdaq', '@Apple', '@Microsoft', '@amazon', '@Google', '@facebook', '@GileadSciences', '@intel']
data = []
# Grab twitter handles and append the name to data
for handle in handles:
    data_dict = {}
    tweets = []
    tweets = api.user_timeline(handle)
    if tweets:
        data_dict['Handle'] = handle
        data_dict['Name'] = tweets[0]['user']['name']
        data.append(data_dict)