【发布时间】:2022-01-21 13:03:13
【问题描述】:
所以,我有这段代码用于在带有字典的列表中添加/减去 x 和 y 值。问题是,代码必须考虑这样一个事实,即字典可以像一个带有引号的字符串一样给出。因此,出于这个原因,我使用ast.literal_eval(point) 将字符串转换为字典。但是,由于某些原因,在命令之后更改的这一行不像其他命令那样工作。
有问题的命令:point['x'] += offset['x'] 和 point['y'] += offset['y']
我很困惑,无论是有问题的问题还是一般的代码,因为它是从 js 翻译的。
import ast
def parse(point):
if type(point) == dict:
return point
else:
return ast.literal_eval(point)
def shift(offset, points):
modified_points = points.copy()
for point in modified_points:
arg_type = type(point)
parse(point)
point['x'] += offset['x']
point['y'] += offset['y']
print(point)
return modified_points
polyline = [
{'x': 0,'y': 0},
{'x': 10, 'y': 10},
'{"x": 20, "y": 20}',
{'x': 30, 'y': 30}
]
results = shift({'x': 10, 'y': -5}, polyline)
print(results)
报错如下:
File "/home/selby/PycharmProjects/10thPractical/3rd.py", line 37, in <module>
results = shift({'x': 10, 'y': -5}, polyline)
File "/home/selby/PycharmProjects/10thPractical/3rd.py", line 19, in shift
point['x'] += offset['x']
TypeError: string indices must be integers
Process finished with exit code 1
【问题讨论】:
-
point是polyline的副本,它是一个字典列表。列表是用数字而不是字符串索引的 -
调用
parse(point)时不存储返回值。