【问题标题】:IndexError: list index out of range in loopIndexError:列表索引超出循环范围
【发布时间】:2019-05-21 15:46:36
【问题描述】:

我正在使用 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)

【问题讨论】:

  • 大概,api.user_timeline(handle) 正在返回一个空列表
  • 在尝试索引之前检查tweets 列表的长度。

标签: python list loops dictionary tweepy


【解决方案1】:

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

 tweets = api.user_timeline(handle)

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

 tweets[0]

这就是您遇到“索引超出范围”问题的原因。

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

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)

【讨论】:

    【解决方案2】:

    发生错误是因为您尝试使用索引 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-23
      • 2023-02-08
      • 1970-01-01
      • 1970-01-01
      • 2011-10-31
      • 2015-06-26
      相关资源
      最近更新 更多