Skip to main content
 首页 » 编程设计

python之类型错误:列表索引必须是整数,而不是 unicode(Telepot 检索名称)

2025年04月02日19grandyang

我试图制作一个机器人来检索群组中聊天发件人的姓名。我将 Python 与 Telepot 结合使用。

>>> from pprint import pprint 
>>> import telepot 
>>> response = bot.getUpdates() 
pprint(response) 
[{u'message': {u'chat': {u'first_name': u'Nick', 
                         u'id': 999999999, 
                         u'last_name': u'Lee', 
                         u'type': u'private'}, 
           u'date': 1444723969, 
           u'from': {u'first_name': u'Nick', 
                     u'id': 999999999, 
                     u'last_name': u'Lee'}, 
           u'message_id': 4015, 
           u'text': u'Hello'}, 
u'update_id': 100000000}] 

当我执行这个时,它给我这个错误

sender1 = response[u'message'][u'from'][u'first_name'] 
sender2 = response[u'message'][u'from'][u'last_name'] 

错误:

TypeError: list indices must be integers, not unicode 

我该如何解决这个问题?

请您参考如下方法:

表示中的方括号表示您有一个列表,列表必须使用整数或切片进行索引。在尝试访问任何包含的词典之前,尝试通过 [0] 建立索引。