让我们假设如下:
sp_sample=[{"t":1434946093036,"v":54.0},{"t":1434946095013,"v":53.0},{"t":1434946096823,"v":52.0}
我希望我能得到以下结果:
sp_sample=[{"t":1434946093036,"v":5400.0},{"t":1434946095013,"v":5300.0},{"t":1434946096823,"v":5200.0}
换句话说,我希望我可以遍历数组并将 v 乘以 100。
以下仅对第一项执行乘法,即产生 54000 :
for i, a in enumerate(sp_sample):
a[i]['v'] = a[i]['v'] * 100
sp_sample
是元组类型。使用以下产生整个数组,这不是我所期望的:
print sp_sample[0]
此外,尝试打印 sp_sample :
print sp_sample
返回以下内容(为简洁起见替换了 .......):
([{'t': 1434946093036, 'v': 54.0}, {'t': 1434946095013, 'v': 53.0}, {'t': 1434946096823, 'v': 52.0}, {'t': 1434946098612, 'v': 52.0}, {'t': 1434946100400, 'v': 51.0}, {'t': 1434946102372, 'v': 49.0},........, {'t': 1434947987823, 'v': 15.0}, {'t': 1434947989851, 'v': 12.0}, {'t': 1434947991899, 'v': 10.0}, {'t': 1434947993744, 'v': 5.0}, {'t': 1434947995599, 'v': 0.0}, {'t': 1434947997455, 'v': 0.0}, {'t': 1434947999494, 'v': 0.0}, {'t': 1434948001542, 'v': 0.0}, {'t': 1434948003417, 'v': 0.0}, {'t': 1434948005264, 'v': 0.0}, {'t': 1434948007120, 'v': 0.0}],)
打印类型(sp_sample)返回:
最佳答案
只需遍历列表并随时更新字典:
sp_sample = [{"t":1434946093036,"v":54.0},{"t":1434946095013,"v":53.0},{"t":1434946096823,"v":52.0}]
for d in sp_sample:
d['v'] *= 100
>>> print(sp_sample)
[{'t': 1434946093036, 'v': 5400.0}, {'t': 1434946095013, 'v': 5300.0}, {'t': 1434946096823, 'v': 5200.0}]
这将依次将列表(元组?)sp_sample
中的每个字典绑定(bind)到 d
,然后您就地对其进行更新。您不需要使用 enumerate()
。
请注意,您确实需要乘以 100,而不是 10000,才能获得您显示的输出。
更新
sp_sample
实际上是一个以字典列表作为唯一项的元组。所以你需要像这样访问元组中的列表:
sp_sample = ([{"t":1434946093036,"v":54.0},{"t":1434946095013,"v":53.0},{"t":1434946096823,"v":52.0}],)
for d in sp_sample[0]: # N.B. access first item of tuple
d['v'] *= 100
>>> print(sp_sample)
[{'t': 1434946093036, 'v': 5400.0}, {'t': 1434946095013, 'v': 5300.0}, {'t': 1434946096823, 'v': 5200.0}]
或者,由于元组只包含一个项目,您可以通过以下方式删除元组:
sp_sample = sp_sample[0]
for d in sp_sample:
d['v'] *= 100
关于python - 如何修改 Python JSON 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33625908/