【问题标题】:Referencing nested dictionary keys and values in dict comprehensions在 dict 理解中引用嵌套的字典键和值
【发布时间】:2014-10-25 02:18:13
【问题描述】:

我今天早些时候问了这个问题:Evaluating values within a dictionary for different keys

我正在使用的字典的结构已经改变,我试图修改我得到的解决方案以适应这种情况。

之前的结构是:

locsOne = {1: [100], 2: [200], 3: [250]}

但现在已经改为:

locsone = {1: [[100]], 2: [[200]], 3: [[250]]}

我正在尝试对 locsOne 字典应用半正弦公式,获取 key:value 到另一个 key:values 的距离,如果它们大于 450,则不应将它们包含在结果字典中。

生成的字典应如下所示:

locsTwo = {1: {2: 100, 3: 150}, 2: {1: 100, 3: 50}, 3: {1: 150, 2: 50}}

这是我收到的代码(感谢 falsetru):

for k1 in locsOne:
    v1 = locsOne[k1][0]
    locsTwo[k1] = {k2: abs(v1 - locsOne[k2][0]) for k2 in locsOne
                   if k1 != k2 and abs(v1 - locsOne[k2][0]) <= 450}
print(locsTwo)

我尝试修改它会返回错误,例如“IndexError: list out of range”和“KeyError”。

我最后的修改是:

for k1 in locsOne:
        v1 = locsOne[k1][1]
        locsTwo[k1] = {k2: harvesineForm(v1 , locsOne[k2][1]) for k2 in locsOne
                   if k1 != k2 and abs(v1 - locsOne[k2][0]) <= 450}

任何帮助将不胜感激。

【问题讨论】:

    标签: python dictionary dictionary-comprehension


    【解决方案1】:
    a = [[100]]
    print a       # [[100]]
    print a[0]    # [100]
    print a[0][0] # 100
    

    假设值总是在列表中包含单个值,嵌套在列表中:

    locsOne = {1: [[100]], 2: [[200]], 3: [[250]]}
    locsTwo = {}
    
    for k1 in locsOne:
        v1 = locsOne[k1][0][0]
        locsTwo[k1] = {k2: abs(v1 - locsOne[k2][0][0]) for k2 in locsOne
                       if k1 != k2 and abs(v1 - locsOne[k2][0][0]) <= 450}
    print(locsTwo)
    

    您只需再次访问列表的第一个值 ([0]),因为您还有一个级别的列表。

    【讨论】:

    • 如果值包含坐标,例如 [-36393612 , 28623927](仅作为示例),是否有办法调整您的建议以适应这种情况?我目前收到“TypeError: unhashable type: 'list'”。
    • dict 到底是什么样的,{1: [-1, 1]}{1: [[-1, 1]]}?甚至{1: [[-1], [1]]}?只是为了确保:只有当列表包含多个元素时才会出现错误,对吧?
    • 看起来像这样:{1:[[-6.26373252, 54.33636358]], 2:[[-6.5463247, 54.4578952]]}
    • 输出应该是什么样子?如果您直接询问您想要什么或建立在我们自己给您的基础上,这将有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 2017-03-01
    • 2020-12-15
    • 1970-01-01
    相关资源
    最近更新 更多