[英]How to fix a TypeError in python
問題是,每當我嘗試運行代碼時,它總是告訴我:“ 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中。 我試圖發出一個存款命令,如果您說“存款”,它將詢問您要存款多少,然后從那里去。
我認為jason_file是list的字典。 就像是:
jason_file = {'money':[某些列表],....依此類推}
因此, money = json_file['money']
將是:
金錢= [部分清單]
如您所見,這里有錢。 它不會接受“銀行”作為索引。 您通過int(money['bank'])
類型強制轉換為int沒關系。
您可以print(money[0])
來檢查它是否確實是列表嗎? 您還可以檢查jason_load是否為列表字典?
您得到的錯誤意味着money['bank']
不是有效的操作,因為money
是列表(而不是dict
)。 因此,只能通過數值指數(訪問它的元素0
, 1
, 2
,...),而不是通過鍵( 'bank'
, 'wallet'
,等)
從您提供的不完整代碼段( 請提供最小,完整和可驗證的示例 )中,我假設您希望您的示例接近以下內容:
>>> 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'>
如您所見, json
模塊正確加載了JSON類型,並為我們保留了Python類型。 您無需強制轉換值(除非字符串包含在...{"wallet": "1234.56"}...
)之內。
仔細檢查您的json_file
包含什么,打印其內容或至少print(type(json_file['money']))
money元素的類型print(type(json_file['money']))
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.