groupby()的问题给出了不同的结果

时间:2014-08-29 04:12:09

标签: python python-2.7

当我改变for循环中两行的顺序时,我不明白为什么会得到两个不同的结果:

def in_degree_distribution(digraph):
    """
    :param digraph: a directed graph, represented as a dictionary
    :return:
    """
    in_degrees = compute_in_degrees(digraph)
    di = sorted(in_degrees.iteritems(), key=itemgetter(1))
    distribution = {}
    for k, g in groupby(di, key=itemgetter(1)):
        print k, map(itemgetter(0), g)
        distribution[k] = len(map(itemgetter(0), g))

    return distribution

我得到了

{0: 0, 1: 0}

但是当我将print语句放在赋值之下时,我得到了不同的结果

def in_degree_distribution(digraph):
    """
    :param digraph: a directed graph, represented as a dictionary
    :return:
    """
    in_degrees = compute_in_degrees(digraph)
    di = sorted(in_degrees.iteritems(), key=itemgetter(1))
    distribution = {}
    for k, g in groupby(di, key=itemgetter(1)):
        distribution[k] = len(map(itemgetter(0), g))
        print k, map(itemgetter(0), g)

    return distribution

在这种情况下,我得到了我想要的输出,但是当我把第一个打印语句放在

时,我不知道为什么g看起来是空的。
{0: 1, 1: 2}

0 个答案:

没有答案