【问题标题】:Why do I get Type Error on one line, but not the others为什么我在一行上出现类型错误,而在其他行上却没有
【发布时间】: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

【问题讨论】:

  • pointpolyline 的副本,它是一个字典列表。列表是用数字而不是字符串索引的
  • 调用parse(point)时不存储返回值。

标签: python typeerror


【解决方案1】:

当你调用parse(point)时,你没有存储返回值,即当你尝试在point['x'] += offset['x']中使用它时point仍然是一个字符串(如错误所示)。

point = parse(point)替换该行,错误就会消失。

【讨论】:

  • 哦,有道理,你有什么解决办法吗?
  • 天啊,非常感谢,解决了它。我想modified_points返回也有类似的问题,现在我只需要弄清楚如何解决它?
  • 我建议在循环遍历原始points 时创建一个空的modified_pointsappend 解析点,而不是制作一个副本并循环遍历该副本。
  • 哦,我试试,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-11
  • 2014-07-26
  • 2015-05-05
  • 1970-01-01
相关资源
最近更新 更多