不想学习hhh 2022-10-29 21:40 采纳率: 85.7%
浏览 21
已结题

关于函数type error的问题

有一个字典a
a = {0: (-37.4168610028693, 145.005372256037),
1: (-37.7032933463858, 144.572524145218),
2: (-37.7292612709136, 144.650631483984),
3: (-37.7777637471456, 144.772303608804),
4: (-37.5792063872414, 144.72816450831)}

我想写一个函数来计算某个点到a字典中所有点的haversine距离并且返回最短距离和字典的key,我的代码如下:

def get_min_dis2(a:dict,b:tuple):
    min_dist = 10000
    for k in a.keys():
        lat1, lon1 = a[k]
        lat2, lon2 = b
        dlat = math.radians(lat2-lat1)
        dlon = math.radians(lon2-lon1)
        a = (math.sin(dlat / 2) * math.sin(dlat / 2) + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2))*
            math.sin(dlon / 2) * math.sin(dlon / 2))
        c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
        distance = c * 6378
        if distance < min_dist:
            min_dist = distance
            key = k
    return (key,b,min_dist)

get_min_dis2(a,(-37.8438,145.0303))
但是我运行时会一直报错TypeError: 'float' object is not subscriptable
请问要如何解决呢

  • 写回答

1条回答 默认 最新

  • 游一游走一走 2022-10-29 22:08
    关注

    你改变a的类型了

    img

    import math
    
    a = {0: (-37.4168610028693, 145.005372256037),
         1: (-37.7032933463858, 144.572524145218),
         2: (-37.7292612709136, 144.650631483984),
         3: (-37.7777637471456, 144.772303608804),
         4: (-37.5792063872414, 144.72816450831)}
    
    
    def get_min_dis2(data: dict, b: tuple):
        min_dist = float('inf')
        for k in data.keys():
            lat1, lon1 = data[k]
            lat2, lon2 = b
            dlat = math.radians(lat2 - lat1)
            dlon = math.radians(lon2 - lon1)
            a = (math.sin(dlat / 2) * math.sin(dlat / 2) + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) *
                 math.sin(dlon / 2) * math.sin(dlon / 2))
            c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
            distance = c * 6378
            if distance < min_dist:
                min_dist = distance
                key = k
        return (key, b, min_dist)
    
    
    print(get_min_dis2(a, (1, 1)))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 11月6日
  • 已采纳回答 10月29日
  • 创建了问题 10月29日

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效