【问题标题】:Using an undefined variable as a dictionary key in python在python中使用未定义的变量作为字典键
【发布时间】:2019-03-05 03:12:08
【问题描述】:

我正在尝试用 Python 重新创建口袋妖怪伤害计算器:https://github.com/Zarel/honko-damagecalc/blob/master/js/data/move_data.js

他的字典以:

开头
var MOVES_RBY = {
    '(No Move)': {
        bp: 0,
        type: 'Normal',
        category: 'Physical'
    },

我的 Python 脚本中有这个,但没有 var,它会返回错误

Traceback(最近一次调用最后一次):文件“”,第 2 行,in NameError: 名称 'bp' 未定义

如何定义bp 以类似方式使用它?

【问题讨论】:

  • 你的代码看起来不像 python
  • 如果你对 Python 不够熟悉,你应该从Python tutorial开始

标签: python dictionary key


【解决方案1】:

在 Javascript 中,字典键被隐式转换为字符串。在 Python 中不是这种情况。所以等效的 Python 代码是:

MOVES_RBY = {
  '(No Move)': {
    'bp': 0,
    'type': 'Normal',
    'category': 'Physical'
  },
}

【讨论】:

    猜你喜欢
    • 2018-10-30
    • 2022-11-14
    • 2021-10-31
    • 1970-01-01
    • 2012-01-07
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多