我有一个字典d
这些键是n
整数。密钥不一定是连续的数字,但是,d
包含范围num_negative
中的(-num_negative,0)
个连续密钥和范围num_positive
中的(0,num_positive)
个连续密钥。我想从它创建另一个字典d2
,其键是[0, n]
范围内的连续整数,给出以下约束:
(1)num_positive
中来自d
组的密钥的元素在d2
中具有相同的密钥。
(2)i
中num_negative
组中具有否定键d
的元素将在n+i
中具有键d2
。< / p>
示例:
# num_positive = 2, num_negative = 3, n=8
# num_positive group = {0,1}
# num_negative gorup = {-3,-2,-1}
d = {-6: 'h', -3: 'a', -2: 'b', -1: 'c', 0: 'd', 1: 'e', 68: 'f', 99: 'g'}
d2 = {0: 'd', 1: 'e', 2: 'g', 3: 'h', 4: 'f', 5: 'a', 6: 'b', 7: 'c'}
答案 0 :(得分:2)
如果我理解正确,具有连续范围之外的键的项目在结果字典中具有未定义的位置。因此,在我的解决方案中,使用在连续范围[0, len(d))
中仍然空闲的任何键,以任意顺序将它们插入到结果字典中。有关更多详细信息,请参阅注释。
from collections import OrderedDict
d = {-6: 'h', -3: 'a', -2: 'b', -1: 'c', 0: 'd', 1: 'e', 68: 'f', 99: 'g'}
remainder = {}
rPos = range(0, 2 + 1) # Positive consecutive range.
rNeg = range(-3, 0) # Negative consecutive range.
n = len(d)
d2 = OrderedDict([(i, None) for i in range(0, n)])
for k, v in d.items():
if k in rNeg: # Checks if in negative consecutive range.
d2[n + k] = v
elif k in rPos: # Checks if in positive negative range.
d2[k] = v
else: # Key is outside of either range.
remainder[k] = v
for k, v in d2.items():
if v is None: # Finds a key still available for use.
# Pops an arbitrary element from the remainder and inserts its
# value into the new dict using an available key.
d2[k] = remainder.popitem()[1]
Input: {-6: 'h', -3: 'a', -2: 'b', -1: 'c', 0: 'd', 1: 'e', 68: 'f', 99: 'g'}
Output: OrderedDict([(0, 'd'), (1, 'e'), (2, 'g'), (3, 'f'), (4, 'h'), (5, 'a'), (6, 'b'), (7, 'c')])
答案 1 :(得分:1)
以下代码应该这样做。
d1={}
for key,val in d.items():
if key in pos and key<=n : #the elements that had a key from the group num_positive in d, will have the same key in d2
d1[key] = val
elif key in neg and ((key+n) in range(n+1)) : #the elements that had a negative key i from the group num_negative in d, will have the key n+i in d2
d1[key+n] = val
#driver values:
IN : n = 8
IN : pos = [0,1]
IN : neg = [-3,-2,-1]
IN : d = {-6: 'h', -3: 'a', -2: 'b', -1: 'c', 0: 'd', 1: 'e', 68: 'f', 99: 'g'}
OUT : d1 = {5: 'a', 6: 'b', 7: 'c', 0: 'd', 1: 'e'}
注意: OP的输出存在一些差异。其中很少有人表现得与定义的不同。
因此,忽略不遵循给定约束的键。