1

我是编程新手,因此感谢所有帮助:给定示例字典

d = {0 : (1, 2, 3), 1 : (2, 3, 4), 2 : (5, 6, 7)}

是否可以使用原始键创建一个新字典,但键的值是值的子值?IE:

0: (1, 2, 3) ---> 0: (4, 5, 6, 7), 1: (5, 6, 7, val(2), val(3))...

所以我希望删除 2,3,因为它们已经包含在 0 的原始值中,依此类推。*另外,我希望替换只进行n

据我了解,这类似于进行细分?

问题是,我必须在一个大字典上执行此操作,而不是使用上面的给定字典,每个键都有给定的值,所以我正在使用

-编辑-

G = {

0:(1,2,3)

1:(3,4,5)

2:(4,5,6)

3:(7,8,9)

...

150:(10,11,12)}

-编辑结束-

k = d.keys()
v = d.values()

for v in k:
    print v " is connected to ", d[v]," by 1 length"

这是一种显示键及其值的迂回方式

-编辑-

所以我想制作一个新字典,新值如下:

G_new = {

0: ((3,4,5),(4,5,6),(7,8,9))

1: ((7,8,9), (值为 4), (值为 5))

...}

然后只保留唯一值并删除键的旧值中包含的值,这样:

G_new_final = {

0:(4,5,6,7,8,9)

1:(7、8、9等)

...} #直到键 150

而且由于我正在处理大量数字,我猜我需要某种函数或字典理解?

-编辑结束-

谢谢!!

4

2 回答 2

1
>>> from collections import defaultdict
>>> a = defaultdict(set)
>>> d = {0: (1, 2, 3), 1: (2, 3, 4), 2: (5, 6, 7)}

#all subvalues of the values of x, no duplicate and without any value of key x
>>> [a[x].update(d.get(y, [])) for x in d for y in d[x]]
>>> [a[x].difference_update(d[x]) for x in d]

#convert it dict of tuple values
>>> {x:tuple(a[x]) for x in a}
{0: (4, 5, 6, 7), 1: (5, 6, 7), 2: ()}
>>> 
于 2013-07-13T04:40:28.293 回答
1
g = {0: (1,2,3),1: (3,4,5),2: (4,5,6),3: (7,8,9)}
g2 = dict()
for key in g.keys():
    old_vals=set(g[key])
    new_vals=[]
    for val in old_vals:
        try:
            new_vals.extend(g[val])
        except KeyError:
            pass
    new_vals = tuple(set(new_vals)-old_vals)
    g2[key]=new_vals

>>> g2
{0: (4, 5, 6, 7, 8, 9), 1: (8, 9, 7), 2: (), 3: ()}

但我看不出这与我之前回答的有什么显着不同?

编辑:有趣的是,这种方法似乎比集合更快?

import time
import random

def makeg(n):
    g=dict()
    for i in xrange(n):
        g[i] = tuple([random.randint(0,n) for _ in xrange(3)])
    return g

g=makeg(100000)

def m(g):
    g2 = dict()
    for key in g.keys():
        old_vals=set(g[key])
        new_vals=[]
        for val in old_vals:
            try:
                new_vals.extend(g[val])
            except KeyError:
                pass
        new_vals = tuple(set(new_vals)-old_vals)
        g2[key]=new_vals
    return g2

s1 = time.time()
m(g)
e1 = time.time()

from collections import defaultdict

def h(g):
    a = defaultdict(set)
    [a[x].update(g.get(y, [])) for x in g for y in g[x]]
    [a[x].difference_update(g[x]) for x in g]
    g2={x:tuple(a[x]) for x in a}
    return g2

s2 = time.time()
h(g)
e2=time.time()

mt =(e1-s1)
ht=(e2-s2)
print mt,ht,mt/ht

nero@ubuntu:~/so$ python so.py 
0.556298017502 0.850471019745 0.654105789129
于 2013-07-13T04:42:11.110 回答