【发布时间】:2012-08-02 02:43:56
【问题描述】:
我正在尝试学习 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
{}
>>>
看起来字典被洗牌了,但在那之后,字典是空的。为什么?还是我用错了?
【问题讨论】:
-
你也应该包含
pick_item的定义。 -
顺便说一下range(n)和range(0, n)是一样的
-
pick_item()是如何实现的?它在字典上调用.popitem()吗?这将修改传递的字典,因此stuff将变为空。一种选择是在shuffle()、dict_to_use = dict_in_question.copy()中创建一个副本。 -
pick_item()可能正在对你的 dict 做一些奇怪的事情(比如删除项目,以免它们再次被选中)。 -
我认为你是对的,因为 pick_item 确实会在选择项目时删除它。但是,下面的解决方案确实有效。
标签: python function dictionary import interpreter