我有一个带有值的12x12字典,对所有人都是0。
matchfield = {}
for i in range(12):
for j in range(12):
matchfield[str((i, j))] = 0
我想使用以下代码段将一些值设置为1(它会检查周围的字段是否空闲):
length = 4
m = randint(1, 10-length)
n = randint(1, 10)
for x in range(m-1, m+length+1):
for y in range(n-1, n+1):
if not matchfield[str((x, y))]:
for k in range(length):
matchfield[str((m+k, n))] = 1
如果我在python控制台中测试它,所有工作和4个选定值都设置为1,但在我的Django视图函数中,我在下一行得到了一个TypeError:
Environment:
Request Method: GET
Request URL: https://www.maik-kusmat.de/schiffeversenken/start/
Django Version: 1.11.5
Python Version: 3.5.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django.contrib.flatpages',
'accounts',
'home',
'contact',
'kopfrechnen',
'braces',
'ckeditor',
'ckeditor_uploader',
'battleship',
'hangman']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware']
Traceback:
File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "/home/pi/Dev/mkenergy/src/battleship/views.py" in battleship_start
36. matchfield[str((m+k, n))] = 1
Exception Type: TypeError at /schiffeversenken/start/
Exception Value: str() argument 2 must be str, not int
我错过了什么吗?我不明白错误
答案 0 :(得分:1)
如果您有
,我希望会出现argument 2 must be str
错误
matchfield[str(m+k, n)]
在Python 3中,str
的第二个参数是编码,因此整数n
会导致该错误。
但是,您的追溯会显示matchfield[str((m+k, n))]
,这不应该导致该错误。尝试重新启动Django服务器以确保您正在运行当前代码。
首先,我建议您使用元组作为字典键,例如
matchfield[(i, j)] = 0
但是,如果您要将matchfield
序列化为json,那么因为键必须是字符串而无法正常工作。