尝试按索引访问列表时出现 Python 错误 - "List indices must be integers, not str"

标签 python

我有以下 Python 代码:

currentPlayers = query.getPlayers()
    for player in currentPlayers:
        return str(player['name'])+" "+str(player['score'])

我收到以下错误:

TypeError: list indices must be integers, not str

我一直在寻找与我接近的错误,但不知道该怎么做,从未遇到过该错误。所以是的,我怎样才能将它转换为整数而不是字符串?我猜问题出在 str(player['score']).

最佳答案

您是否希望 player 成为 dict 而不是 list

>>> player=[1,2,3]
>>> player["score"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>> player={'score':1, 'age': 2, "foo":3}
>>> player['score']
1

关于尝试按索引访问列表时出现 Python 错误 - "List indices must be integers, not str",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14198821/

相关文章:

python - Django:摆脱内容类型的 RemovedInDjango19Warning

python - 使用 Altair 和 Jupyter 绘图时如何在轴标签中显示希腊字母?

c++ - 为什么我的 setup.py 脚本会出现此错误?

python - 使用 Python 将标准 JSON 文件转换为 json-serde 格式并上传到 Amazon Athena 的 AWS S3 存储桶(Presto、Hive)

python 如何显示已 checkin 的复选框

python - 当销毁 TreeView 时,我应该 'destroy' 一个列表存储( TreeView 的模型)吗?

python - 针对 API 版本编译的模块

python - 如何使用 python-binance 获取历史买入价和卖出价

python - 如何在airflow中设置多个Dag目录

python - 选择同名的 2nd DIV CLASS - Python Selenium