在Python中没有得到所需的输出

2024-04-20 06:00:48 发布

您现在位置:Python中文网/ 问答频道 /正文

def dict_invert(d):
    '''
    d: dict
    Returns an inverted dictionary according to the instructions above
    '''
    result = {}

    for k, v in d.iteritems():
        result.setdefault(v, []).append(k)

    return result

在上述程序中,所有输出都是正确的

^{pr2}$

但根据我的赋值,我需要{6: [2, 4, 6, 8]}作为输出。 我该怎么办?在


Tags: thetoinanfordictionarydefresult
2条回答

items()¶

Return a copy of the dictionary’s list of (key, value) pairs.

CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

这同样适用于iteritems

Source

请尝试在附加后对其进行排序,如下所示:

def dict_invert(d):
    '''
    d: dict
    Returns an inverted dictionary according to the instructions above
    '''
    result = {}

    for k, v in d.iteritems():
        result.setdefault(v, []).append(k)
        result[v].sort()

    return result

更新:

由于python的算法Timsort适合对已经排序的数据进行排序,因此效率会很高。 如果您希望获得更高的效率,您可以使用^{}

^{pr2}$

由于数据不是很大,而且没有任何复杂的自定义相等运算符(这是一个int比较),我相信您几乎看不到任何区别。在

不过,将dict重新创建为已排序的dict将浪费空间和CPU时间,因此不建议这样做。在

更新2:

带基准的代码:

import bisect
import timeit

d = {2: "6", 4: "6", 6: "6", 8:"6"}

def dict_invert(d):
    '''
    d: dict
    Returns an inverted dictionary according to the instructions above
    '''
    result = {}

    for k, v in d.iteritems():
        bisect.insort(result.setdefault(v, []), k)

    return result

def dict_invert2(d):
    '''
    d: dict
    Returns an inverted dictionary according to the instructions above
    '''
    result = {}

    for k, v in d.iteritems():
        result.setdefault(v, []).append(k)
        result[v].sort()

    return result

def dict_invert3(d):
    '''
    d: dict
    Returns an inverted dictionary according to the instructions above
    '''
    result = {}

    for k, v in d.iteritems():
        result.setdefault(v, []).append(k)

    return {k: sorted(v) for k, v in result.iteritems()}

print(timeit.timeit("dict_invert(d)", setup="from __main__ import dict_invert, d"))
print(timeit.timeit("dict_invert2(d)", setup="from __main__ import dict_invert2, d"))
print(timeit.timeit("dict_invert3(d)", setup="from __main__ import dict_invert3, d"))

python 2的输出:

2.4553718788
2.59005746839
2.88147985275

python3的输出(将iteritems()更改为items()):

2.56672796628521
2.999647860343478
3.4022091183182583

相关问题 更多 >