如何动态创建N个元素的字典?

时间:2018-07-05 17:46:01

标签: python dictionary

我正在尝试创建数量为N的组的列表(此数字是我的函数的参数)。

基本上,我想即时创建N组乐谱,例如,如果我将N指定为3,它将创建一个包含N组乐谱的字典。这是硬编码的版本:

groups = [(1, 1, 1, 1)]
levels_list = []
for group in groups:
    level0 = 0
    scores = [0,1,2,3,4,5,6,7,8]
    level1 = scores[int(max(level0) + 1): int((max(level0) + 1) + group[1])]
    level2 = scores[int(max(level1) + 1): int((max(level1) + 1) + group[2])]
    level3 = scores[int(max(level2) + 1): int((max(level2) + 1) + group[3])]
    levels = {'nothing': level0, 'one_thing': level1, 'several_things': level2, 'loads_of_things': level3}
    levels_list.append(levels)

我假设使用伪代码,其中N是参数“ self.params.n_groups”,如下所示:

levels_dict = {}
for group in groups:
    levels = [0] # initialize a list with the first level as 0
    scores = [0,1,2,3,4,5,6,7,8]
    level = self.create_levels(levels, group, scores)
    levels_dict[level] = level

def create_levels(self, levels, group, scores):
     for n in range(self.params.n_groups):
         # how to write this part?
​         level = grades[int(max(levels[i]) + 1): int((max(levels[i]) + 1) + group[i+1])]
    return level

我在create_levels函数上遇到困难,特别是在调用level {n}时遇到困难(如果我对它应用格式,则它不会被识别为现有变量,而是一个字符串)。我需要将先前的“ level”变量(level0,level1,level2等)动态插入该计算中。

0 个答案:

没有答案