Facing this error :- TypeError: unsupported operand type(s) for -: 'str' and 'float'?

Facing this error :- TypeError: unsupported operand type(s) for -: 'str' and 'float'?

查询) 我试图使用 dict_A 中提到的坐标绘制图表,但操作停止显示错误

TypeError: unsupported operand type(s) for -: 'str' and 'float'.

import json
import matplotlib.pyplot as plt
from ast import literal_eval


def any_function():

    with open('contents.txt') as f:
        A               = f.readline()  
        dict_A          = json.loads(A)         # converts to dictionary

        B = dict((literal_eval, i) for i in dict_A.items()) #convert k, v to int

#plotting a simple graph-based on coordinates mentioned in A.

        x = [i[0]  for i in  B.values()]
        y = [i[1]  for i in  B.values()]
        size = 50
        offset = size/100.
        for i, location in enumerate(zip(x,y)):
            plt.annotate(i+1, ( location[0]-offset, location[1]-offset), zorder=10 )  
        
    return {'A':dict_A}
    

any_function()                 #calling the function 


这是我在文本文件中的数据(contents.txt)

{"1":"[0,0]", "2":"[5, 0]", "3":"[6,0]","4":"[3,5]"}

出错

runfile('D:/python programming/a new program 2021/testing 9 input.py', wdir='D:/python programming/a new program 2021')
Traceback (most recent call last):

  File "D:\python programming\a new program 2021\testing 9 input.py", line 37, in <module>
    a = any_function()

  File "D:\python programming\a new program 2021\testing 9 input.py", line 32, in any_function
    plt.annotate(i+1, ( location[0]-offset, location[1]-offset), zorder=10 )

TypeError: unsupported operand type(s) for -: 'str' and 'float'

我不确定你认为这是在做什么,但这不是你所期望的:

B = dict((literal_eval, i) for i in dict_A.items()) #convert k, v to int

这不会将任何内容转换为 int。那里面的部分:

(literal_eval, i)

将生成一个元组,其中包含 literal_eval 函数对象和字典中的项目对。我猜你没有 print(B) 看看你在建造什么。由于所有项目都具有相同的密钥,因此您最终得到的是:

>>> B = dict((literal_eval, i) for i in t.items()) #convert k, v to int
>>> B
{<function literal_eval at 0x7f531ddcb5e0>: ('4', '[3,5]')}

你真正想要的是 CALL literal_eval:

>>> B = dict((literal_eval(k), literal_eval(v)) for k,v in t.items())
>>> B
{1: [0, 0], 2: [5, 0], 3: [6, 0], 4: [3, 5]}
>>>