如何在python

时间:2019-02-14 03:44:55

标签: python typeerror

问题是,每当我尝试运行代码时,它总是告诉我: “ TypeError:列表索引必须是整数或切片,而不是str”

您可以在代码中看到,我已经尝试在银行/钱包金额周围添加int()。

with open("accounts/" + username + ".json") as file:
    json_file = json.load(file)
    money = json_file['money']
    bank = int(money['bank'])
    wallet = int(money['wallet'])
    if wallet >= deposit_amount:
        new_bank = bank + deposit_amount
        new_wallet = wallet - deposit_amount
        money['bank'] = new_bank
        json_file['wallet'] = new_wallet
        dump_file = open("accounts/" + username + ".json", 'w')
        json.dump(json_file, dump_file)
    else:
        print("You do not have enough money for that!")


File "C:/Users/riley/PycharmProjects/BankManager/main.py", line 20, in <module> startup()
File "C:/Users/riley/PycharmProjects/BankManager/main.py", line 12, in startup login()
File "C:\Users\riley\PycharmProjects\BankManager\handlers\AccountHandler.py", line 16, in login set_panel(username)
File "C:\Users\riley\PycharmProjects\BankManager\handlers\PanelHandler.py", line 9, in set_panel start_panel(username)
File "C:\Users\riley\PycharmProjects\BankManager\panels\user.py", line 29, in start_panel bank = int(money['bank'])

我正在用python创建Money System,因此以后可以将其实现为Discord Bot。我试图发出一个存款命令,如果您说“存款”,它将询问您要存款多少,然后从那里去。

2 个答案:

答案 0 :(得分:0)

我认为jason_file是list的字典。像这样:

jason_file = {'money':[某些列表],....依此类推}

因此,money = json_file['money']的结果将是:

金钱= [某些列表]

如您所见,这里有钱。它不会接受“银行”作为索引。您用int(money['bank'])将类型强制转换为int没关系。

您能print(money[0])检查它是否确实是列表吗?您还可以检查jason_load是否为列表字典?

答案 1 :(得分:0)

您收到的错误意味着money['bank']不是有效的操作,因为money是一个列表(而不是dict)。因此,您只能通过数字索引(012,...)而不是通过键('bank''wallet'来访问其元素等)

从您提供的不完整摘录中(请提供Minimum, Complete, and Verifiable Example ),我认为您希望您的示例与以下内容接近:

>>> import json
>>> json_string = '{"money": {"bank": "a bank", "wallet": 1234.56}}'
>>> json_data = json.loads(json_string)
>>> json_data
{"money": {"bank": "a bank", "wallet": 1234.56}}
>>> type(json_data['money'])
<class 'dict'>
>>> type(json_data['money']['wallet'])
<class 'float'>

如您所见,the json module loads the JSON type properly使我们保留了Python类型。您无需强制转换值(除非包含在...{"wallet": "1234.56"}...之类的字符串中)。

仔细检查您的json_file所包含的内容,打印其内容或至少显示货币元素print(type(json_file['money']))的类型。