0

这有点令人费解,所以如果我错过了一个简单的构造,请告诉我:)

我正在分析一些匹配实验的结果。在游戏结束时,我希望能够查询诸如之类的东西experiments[0]["cat"]["cat"],这会产生“cat”与“cat”匹配的次数。experiments[0]["cat"]["dog"]相反,当第一个查询是一只猫并且匹配尝试是一只狗时,我可以这样做。

以下是我填充此结构的代码:

    # initializing the first layer, a list of dictionaries.
    experiments = []
    for assignment in assignments:
        match_sums = {}
        experiments.append(match_sums)


for i in xrange(len(classes)):
        for experiment in xrange(len(experiments)):
            # experiments[experiment][classes[i]] should hold a dictionary,
            # where the keys are the things that were matched against classes[i], 
            # and the value is the number of times this occurred.
            experiments[experiment][classes[i]] = collections.defaultdict(dict)

            # matches[experiment][i] is an integer for what the i'th match was in an experiment.
            # classes[j] for some integer j is the string name of the i'th match. could be "dog" or "cat".
            experiments[experiment][classes[i]][classes[matches[experiment][i]]] += 1
            total_class_sums[classes[i]] = total_class_sums.get(classes[i], 0) + 1

    print experiments[0]["cat"]["cat"]
    exit()

很明显,这有点令人费解。最后一场比赛我得到的值为“1”,而不是完整的字典experiments[0]["cat"]。我做错了吗?这里的错误可能是什么?抱歉,您的疯狂并感谢您提供任何可能的帮助!

4

2 回答 2

2

两点:

  • 字典键可以是元组;和
  • 如果您要计算事物,请使用collections.Counter. (您可以使用defaultdict(int),但Counter更有用。)

所以,而不是

experiments[experiment][classes[i]][classes[matches[experiment][i]]] += 1

experiments = Counter()
...
experiments[experiment, classes[i], classes[matches[experiment][i]]] += 1
于 2012-08-09T20:40:11.890 回答
0

我只是想猜测你的需求,所以我试图改变你的尺寸顺序。

for className, classIdx in enumerate(classes):
    experiment = collections.defaultdict(list)
    experiments[className] = experiment
    for assignment,assignmentIdx in enumerate(assignments):
        counterpart = classes[matches[assignmentIdx][classIdx]]
        experiment[counterpart].append((assignment,assignmentIdx))

print(len(experiments["cat"]["cat"]), len(experiments["cat"]))
于 2012-08-09T20:58:45.093 回答