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

how to store lists as values in python defaultdict lists

有没有办法将坐标存储为字典中的元组或列表? 我创建了一个字典,将(与原点的距离)作为键,将(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]]})

你能试试这个代码吗? 我基本上改变了 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