1

我不确定以前是否有人问过这个问题,因为我也不知道如何措辞:

因此,例如,我有一个给定的带有键和值的字典:

d = {[ 0 : 1, 2, 3], [1 : 2, 3, 4], [2: 5, 6, 7]}

我想证明 1 是一个键,也是一个值,从而得出结论 0 与 1 的值有关。比如 [0:[2,3,4], 2, 3] 或类似的东西那。

我会为大量的键执行此操作,每个键都有多个值。

这可能吗?我将如何编码?顺便说一句,我对 Python 很陌生,所以请放轻松。

4

2 回答 2

0

你的意思是这样的吗?

d = { 0 : (1, 2, 3) , 1 : (2, 3, 4), 2: (5, 6, 7)}
for key in d.keys():
    for val in d[key]:
        try:
            d[key]+=d[val]
        except KeyError:
            pass

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

如果您想要唯一值,请添加d[key] = tuple(set(d[key]))for key in d.keys()循环的末尾。

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

ps:d = {[ 0 : 1, 2, 3], [1 : 2, 3, 4], [2: 5, 6, 7]}不是有效的python!

编辑:见评论。

d = { 0 : [1, 2, 3] , 1 : [2, 3, 4], 2: [5, 6, 7]}
for key in d.keys():
    orig_vals=d[key]
    new_vals=[]
    for val in orig_vals:
        try:
            new_vals+=d[val]
        except KeyError:
            pass
    d[key] = list(set(new_vals)-set(orig_vals))

>>> d
{0: [4, 5, 6, 7], 1: [5, 6, 7], 2: []}

如果您想避免清除未链接到其他键的值,例如 2 中的 [5,6,7],则将最后一行更改为

if new_vals:
        d[key] = list(set(new_vals)-set(orig_vals))

这使

>>> d
{0: [4, 5, 6, 7], 1: [5, 6, 7], 2: [5, 6, 7]}

编辑2:见评论。

d = { 0 : [1, 2, 3] , 1 : [2, 3, 4], 2: [5, 6, 7]}
for key in d.keys():
    orig_vals=d[key]
    new_vals=[]
    count = 0
    for val in orig_vals:
        try:
            new_vals+=d[val]
            count+=1
            if count >= yournumberhere: break
        except KeyError:
            pass
    d[key] = list(set(new_vals)-set(orig_vals))
于 2013-07-12T14:39:15.113 回答
0
d = {[ 0 : 1, 2, 3], [1 : 2, 3, 4], [2: 5, 6, 7]} this is not a valis dictionary

It will be like this:

d={0: [1, 2, 3], 1: [2, 3, 4], 2: [5, 6, 7]}
arr=[]
for val in d.values():
       arr.extend(val)



arr = [1, 2, 3, 2, 3, 4, 5, 6, 7]

values=set(arr) #removeing repeted element from the list
value = [1, 2, 3, 4, 5, 6, 7]

result = [key for key in d.keys() if key in values] #will return the result
result = [1, 2]

here result = [1,2] so,1 and 2 is a key and also a vaule
于 2013-07-12T14:50:09.413 回答