基于其他字典python递归生成字典

时间:2018-08-08 07:09:15

标签: python python-3.x list dictionary recursion

我正在尝试递归生成格言,我是说我有格言:

{98: [38, 39, 40, 41], 99: [38, 39, 40, 41], 100: [38, 39, 40, 41, 42]}

我想获得新的命令,

其中

new_key = old_key*2, new_value = list(range(2*old_value[0], 2*(old_value[-1] + 1)))

new_key = old_key*2 + 1, new_value = list(range(2*old_value[0], 2*(old_value[-1] + 1)))

因此,我想从键= 98中获得键196、197和

values = list(range(2*old_value[0], 2*(old_value[-1] + 1)))

例如下一个

{196: [76, 77, 78, 79, 80, 81, 82, 83], 197: [76, 77, 78, 79, 80, 81, 82, 83], 198: [76, 77, 78, 79, 80, 81, 82, 83], 199: [76, 77, 78, 79, 80, 81, 82, 83], 200: [76, 77, 78, 79, 80, 81, 82, 83, 84, 85], 201: [76, 77, 78, 79, 80, 81, 82, 83, 84, 85]}

,依此类推 也许有任何想法如何做到这一点?任何帮助将不胜感激!

更新:

我不仅要获取下一个字典,还要获取多个字典,因此该规则适用于该下一个字典

new_key = old_key * 2,new_value = list(range(2 * old_value [0],2 *(old_value [-1] + 1)))

new_key = old_key*2 + 1, new_value = list(range(2*old_value[0], 2*(old_value[-1] + 1)))

其中old_key,old_value是上一字典的项目(后退)

也许答案接近

n = 1
while n < 3:
    rl = [{x*2**n: list(range(2**n*y[0], 2**n*(y[-1]+1))), x*2**n+1: list(range(2**n*y[0], 2**n*(y[-1]+1)))} for x, y in tiles_dict.items()]
    n += 1
    req_dict = {}
    for d in rl:
        req_dict.update(d)
    print(req_dict)

我正在尝试

2 个答案:

答案 0 :(得分:0)

您可以使用list comprehension来实现

d = {98: [38, 39, 40, 41], 99: [38, 39, 40, 41], 100: [38, 39, 40, 41, 42]}

# list-comprehension outputs a list of dictionaries
rl = [{x*2:list(range(2*y[0], 2*(y[-1]+1))), x*2+1:list(range(2*y[0], 2*(y[-1]+1)))} for x,y in d.items()]

# flattening the list of dictionaries
req_dict = {}
for d in rl:
    req_dict.update(d)

输出:

req_dict 
{196: [76, 77, 78, 79, 80, 81, 82, 83], 197: [76, 77, 78, 79, 80, 81, 82, 83], 198: [76, 77, 78, 79, 80, 81, 82, 83], 199: [76, 77, 78, 79, 80, 81, 82, 83], 200: [76, 77, 78, 79, 80, 81, 82, 83, 84, 85], 201: [76, 77, 78, 79, 80, 81, 82, 83, 84, 85]}

答案 1 :(得分:0)

基于@Van Peer的想法,我明白了

# looping over range 1 to 5
for n in range(1, 5):
    rl = [{x*(2**n): list(range((2**n)*y[0], (2**n)*(y[-1]+1))), x*(2**n)+1: list(range((2**n)*y[0], (2**n)*(y[-1]+1)))} for x, y in tiles_dict.items()]

req_dict = {}
for d in rl:
    req_dict.update(d)
print(req_dict)