2

我正在尝试学习python(具有VBA背景)。

我已将以下函数导入到我的解释器中:

def shuffle(dict_in_question):  #takes a dictionary as an argument and shuffles it
    shuff_dict = {}
    n = len(dict_in_question.keys())
    for i in range(0, n):
        shuff_dict[i] = pick_item(dict_in_question)
    return shuff_dict

以下是我的口译员的打印件;

>>> stuff = {"a":"Dave", "b":"Ben", "c":"Harry"}
>>> stuff
{'a': 'Dave', 'c': 'Harry', 'b': 'Ben'}
>>> decky11.shuffle(stuff)
{0: 'Harry', 1: 'Dave', 2: 'Ben'}
>>> stuff
{}
>>> 

看起来字典被打乱了,但在那之后,字典是空的。为什么?或者,我用错了吗?

4

2 回答 2

3

您还需要将其分配回东西,因为您要返回一本新字典。

>>> stuff = decky11.shuffle(stuff)
于 2012-08-04T05:12:08.750 回答
0

Dogbert 的回答解决了您的直接问题,但请记住,字典没有顺序!没有“my_dict 的第一个元素”这样的东西。(使用 .keys() 或 .values() 会生成一个列表,该列表确实有顺序,但字典本身没有。)因此,谈论“洗牌”字典并没有真正的意义。

All you've actually done here is remapped the keys from letters a, b, c, to integers 0, 1, 2. These keys have different hash values than the keys you started with, so they print in a different order. But you haven't changed the order of the dictionary, because the dictionary didn't have an order to begin with.

Depending on what you're ultimately using this for (are you iterating over keys?), you can do something more direct:

shufflekeys = random.shuffle(stuff.keys())
for key in shufflekeys:
    # do thing that requires order

As a side note, dictionaries (aka hash tables) are a really clever, hyper-useful data structure, which I'd recommend learning deeply if you're not already familiar. A good hash function (and non-pathological data) will give you O(1) (i.e., constant) lookup time - so you can check if a key is in a dictionary of a million items as fast as you can in a dictionary of ten items! The lack of order is a critical feature of a dictionary that enables this speed.

于 2012-08-04T18:31:50.490 回答