0

我将一组任意索引映射到索引从 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在这里所说的,但我得到了键和值交换,最后是一个 -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}
4

1 回答 1

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}
于 2013-08-21T17:16:35.783 回答