使用字典作为0基于索引的集合

时间:2013-08-21 16:03:18

标签: python dictionary set

我将一组任意索引映射到索引从0开始的另一个集合。目前我已经完成了所以使用以下代码(密码是解决方案):

[In]  t = [(3, 1, 2, 2), (3, 2, 4, 4), (6, 3, 4, 4)]  ## Original set indexes
[Out] r =  set ([i for sublist in t for i in sublist] )
[In]  r =  set([1, 2, 3, 4, 6])                       ## Set of indexes
[In]  cipher = dict(zip(r, range(len(r))))
[Out] cipher {1: 0, 2: 1, 3: 2, 4: 3, 6: 4}           ## Solution (Mapping key)

然而,由于字典中的键必须是唯一的,我试图在不使用集合的情况下创建“密码”。

[In]  t = [(3, 1, 2, 2), (3, 2, 4, 4), (6, 3, 4, 4)]  ## Original set indexes
[Out] r =  [i for sublist in t for i in sublist] 
[In]  r =  [3, 1, 2, 2, 3, 2, 4, 4, 6, 3, 4, 4]       ## Flattened list
[In]  cipher = dict(zip(r, 'count +1 for each new key' ))
[Out] cipher {1: 0, 2: 1, 3: 2, 4: 3, 6: 4}           ## Mapping key

因此,对于添加到字典中的每个键,添加一个等于当时字典长度的值。我不知道这是否可能?

编辑

我做了Martijn Pieters所说的here,但我得到的是键和值交换,最后是-1键。这对我来说似乎有点太进步了,所以我只会选择我拥有的东西。

from collections import defaultdict
from itertools import count
from functools import partial

keymapping = defaultdict(partial(next, count(-1)))
outputdict = {keymapping[v]: v for v in r}

[Out] {0: 2, 1: 3, 2: 4, 3: 6, -1: 1}

1 个答案:

答案 0 :(得分:0)

确定。

>>> t = [(3, 1, 2, 2), (3, 2, 4, 4), (6, 3, 4, 4)]

首先,你希望这些被夷为平地:

>>> from itertools import chain
>>> flattened = chain(*t)

然后制作成套

>>> index_set = set(flattened)
>>> index_set
set([1, 2, 3, 4, 6])

然后对它进行排序(集合未排序)

>>> index_list = sorted(index_set)

然后想在这里为每个数字分配一个0的新值

>>> cipher = { k: v for i in v, k in enumerate(index_list) }
>>> cipher
{1: 0, 2: 1, 3: 2, 4: 3, 6: 4}