如何将列表存储为python defaultdict列表中的值

时间:2015-10-24 07:34:15

标签: python defaultdict

有没有办法将坐标存储为字典中的元组或列表? 我创建了一个字典,它将(距离原点的距离)作为键和(x,y中的坐标)作为值。但是,如果我尝试将多个坐标附加到相同的距离,它将覆盖。

到目前为止,这是我的代码:

import math
from collections import defaultdict
origin_x = 0.0
origin_y = 0.0

P = [(0,1),(1,0),(1,0)]
k = 2

xmid = float(sum(P[:][0]))/len(P)

xleft = [x for x in P[:][0] if x <= xmid]
xright = [x for x in P[:][0] if x > xmid]

Pleft = [(x,y) for x,y in P[:] if x <= xmid ]
Pright = [(x,y) for x,y in P[:] if x > xmid]

print Pleft

def dist(x1,y1):
    return math.sqrt((x1-origin_x)**2 + (y1-origin_y)**2)

worst = []
nearest = defaultdict(list)

for l in xrange(0,len(Pleft)):
    curr = dist(Pleft[l][0], Pleft[l][1])
    print curr
    if len(nearest) > 1:
        worst[0] = sorted(nearest.keys())[len(nearest)]

    if len(nearest) <= k:
        nearest[curr]= Pleft[l]
    else:
        if curr < worst[0]:
            nearest[curr].append(Pleft[l])
        else:
            break
    #nearest
        #best[0] = curr
        #best[1] = (Pleft[l])

for r in xrange(0,len(Pright)):
    curr = dist(Pright[r][0],Pright[r][1])
    if len(nearest) > 1:
        worst[0] = sorted(nearest.keys())[len(nearest)-1]
    if len(nearest) <= k:
        nearest[curr] = Pright[r]
    else:
        if curr < worst[0]:
            nearest[curr].append(Pright[r])
        else:
            break

print nearest

以下代码有效:

>> nearest[2.99].append([2,3])

>> nearest
Out[70]: defaultdict(<type 'list'>, {1.0: [1, 0], 2.0: [1, 2], 4.8: '[3, 1]', 2.99: [[2, 3]]})

1 个答案:

答案 0 :(得分:0)

你可以试试这段代码吗? 我基本上改变了nearest[curr].append(P[left)而不是nearest[curr] = p[left] ......用一个元组取代了列表...... 你也不必在P [:] [0]中为x做x,你可以这么做:

x for x in P[0]

试试这个并告诉我它是否解决了你的问题......

from collections import defaultdict
origin_x = 0.0
origin_y = 0.0

P = [(0,1),(1,0),(1,0)]
k = 2

xmid = float(sum(P[0]))/len(P)

xleft = [x for x in P[0] if x <= xmid]
xright = [x for x in P[0] if x > xmid]

Pleft = [(x,y) for x,y in P if x <= xmid ]
Pright = [(x,y) for x,y in P if x > xmid]

print Pleft

def dist(x1,y1):
    import math
    return math.sqrt((x1-origin_x)**2 + (y1-origin_y)**2)

worst = []
nearest = defaultdict(list)

for l in xrange(0,len(Pleft)):
    curr = dist(Pleft[l][0], Pleft[l][1])
    print curr
    if len(nearest) > 1:
        worst[0] = sorted(nearest.keys())[len(nearest)]

    if len(nearest) <= k:
        nearest[curr].append(Pleft[l])
    else:
        if curr < worst[0]:
            nearest[curr].append(Pleft[l])
        else:
            break
    #nearest
        #best[0] = curr
        #best[1] = (Pleft[l])

for r in xrange(0,len(Pright)):
    curr = dist(Pright[r][0],Pright[r][1])
    if len(nearest) > 1:
        worst[0] = sorted(nearest.keys())[len(nearest)-1]
    if len(nearest) <= k:
        nearest[curr].append(Pright[r])
    else:
        if curr < worst[0]:
            nearest[curr].append(Pright[r])
        else:
            break

print nearest