gpt4 book ai didi

python - 使用旧键但包含子值创建新字典

转载 作者:行者123 更新时间:2023-12-01 05:40:40 26 4
gpt4 key购买 nike

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

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

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

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), (values of 4), (values of 5))

...}

然后仅保留唯一值并删除旧 key 值中包含的值,以便:

G_new_final = {

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

1: (7,8,9, etc.)

...} #until key 150

由于我正在处理很多数字,我猜我需要某种函数或字典理解?

-编辑结束-

谢谢!!

最佳答案

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: ()}

但我不明白这与我的 answered previously? 有什么显着不同

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

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

关于python - 使用旧键但包含子值创建新字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17626904/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com