0

这是我用来尝试将列表附加到 json 文件的测试程序。实际的主程序将不断地将具有不同值的相同列表附加到其 json 文件中。在这里,我通过尝试附加列表的 5 个实例来对其进行测试。尝试运行时,我不断收到错误“无法读取 null 的属性 'indexOf'”。

我试过用print(mapping)它来查看它失败的地方,它从未执行过该命令。我不确定这只是我的代码还是其他东西,但程序根本没有运行。使用 VSCode 的调试器时,我得到“无法读取 null 的属性 'indexOf'”,当从终端运行时,程序似乎完全冻结而没有输出。

import json as js
import numpy as np
from os import time

resolution = 200 # Map resolution: Max = 200
step = [None for _ in range(resolution)] # Angle/Step list
dist = [None for _ in range(resolution)] # Distance list
mapping = [step, dist] # Mapping distances do steps/angles

print(mapping)

with open("test.json", "a") as test:
    ps.dumps(os.time(), test)
    for turn in range(5):
        for num in range(resolution):
            step[num] = num
            dist[num] = np.random()
            js.dumps(mapping, test)
4

1 回答 1

-1

当你在外面声明一个变量时,它不会像它的内容那样改变。尝试将mapping声明放入循环中,看看会发生什么。

或者做

js.dump(list(step[num], dist[num]), test)

编辑:看来我错了。我现在对其进行了测试,并得到了可以在 python3 中使用的东西:

import json
import numpy
resolution = 200 # Map resolution: Max = 200
step = [None for _ in range(resolution)] # Angle/Step list
dist = [None for _ in range(resolution)] # Distance list
mapping = list()

with open("test.json", "a") as test:
    for turn in range(5):
        for num in range(resolution):
            step[num] = num
            dist[num] = numpy.random.random()
        mapping = [step, dist]
        json.dump(mapping, test)
        test.write(',\n')

注意事项:

1. json.dump instead of json.dumps for writing into file
2. declared mapping as an empty list that gets declared after the loop
3. also write a ',\n' to the json file to make it more readable

我也会在评论中尽我所能提供帮助,对于最初的弱回答感到抱歉。

于 2019-05-12T06:01:16.437 回答