字典:唯一的相对值,其中值是列表类型

时间:2016-06-29 20:28:34

标签: python-2.7 dictionary nlp tensorflow text-classification

我以下列格式获取word2vec_basic.py的输出

最接近key1:node1,node2,node3 .. 最接近key2:node2,node4,node5 ..

这意味着node2比key1更接近key2(如果我错了,请纠正我,因为我是新手)

如果我得到以下格式的输出

会很棒

最近的key1:node1,node3,node6 .. 最接近key2:node2,node4,node5 ..

即,仅考虑最近邻居进行群集。

同样的建议?

我正在维护一个python字典,其格式如下:

{
key1: [node1,node2,node3],
key2: [node2,node4,node5]
}

但我要求,

 {
    key1: [node1,node3,node6],
    key2: [node2,node4,node5]
    }

对于上面的词典,我将需要

Nearest to key1  : node1, node3 , node6..
Nearest to key2 : node2, node4, node5 ..

我们可以在tensorflow本身中这样做,还是应该定义一个将字典作为输入并给我所需输出的函数?

例如: 如果我们有一个以下格式的python字典:

{ 
   a: ["abc","bcd","def"],
   b: ["def","xyz"]
}

这里的值是列表。我正在从上面的输入中寻找以下格式:

{ 
    a: ["abc","bcd"],
    b: ["def","xyz"]
}

欢迎提出如何实现这一目标的建议。

此外,在内置函数中是否有任何python可以帮助我达到上述输出格式?

2 个答案:

答案 0 :(得分:0)

dicts 是无序的,因此无法保证删除哪个dupe但是您可以保留 set 元素,只要您迭代这些项目,更新/删除元素来自列表/值,如果已经看到

d = {
  "a": ["abc","bcd","def"],
   "b": ["def","xyz"]
}
seen = set()
for k,v in d.items():
    d[k] = [seen.add(ele) or ele for ele in v if ele not in seen]

print(d)

这可以输出:

{'b': ['def', 'xyz'], 'a': ['abc', 'bcd']}

或者:

 d = { "a": ["abc","bcd","def"], "b": ["xyz"]}

这完全取决于你先击中哪个键。

正如您从this top answer看到的436个upvotes,删除逻辑是有效的,并且如果需要它维护订单。另外,为了避免每次在链接中进行 set.add 查找,您可以设置seen_add = seen.add并使用seen._add(ele)代替seen.add

答案 1 :(得分:0)

由于Python中的词典条目是无序的,因此您需要首先构建一个单独的字典键入的字典,记录它所在的每个列表(或序列)以及该列表中的索引,以便将每个列表中的相对距离与一个列表进行比较另一个。完成之后,可以引用它来确定每个节点是否应该留在它所在的每个列表中,方法是再次通过字典的内容。

d = {
   "a": ["abc", "bcd", "def"],
   "b": ["def", "xyz"]
}

def check_usage(k, elem_usage):
    if len(elem_usage) == 1:  # unique?
        return True
    else:
        index = elem_usage[k]  # within this elem's seq
        for key,value in elem_usage.items():
            if key != k:
                if value < index:
                    return False
        else:
            return True

usage = {}
for key in d:  # build usage dictionary
    for index, item in enumerate(d[key]):
        usage.setdefault(item, {})[key] = index

for k,seq in d.items()::  # remove nodes that are closer in other lists
    d[k] = [elem for elem in seq if check_usage(k, usage[elem])]

# display results
print('{')
for k in sorted(d):
    print('    {!r}: {},'.format(k, d[k]))
print('}')

输出:

{                      
    'a': ['abc', 'bcd'],
    'b': ['def', 'xyz'],
}                      
相关问题