从字典中随机删除项目 [英] Removing items randomly from a dictionary
问题描述
如何从Python中的字典中删除随机项目?
How do I remove random items from a dictionary in Python?
我必须从字典中删除指定数量的项目,因此我尝试使用 dict.popitem
我认为是随机的,但似乎不是。
I have to remove a specified number of items from a dictionary and so I tried to use dict.popitem
which I thought was random, but it is seems it is not.
作为 docs 说:
从字典中删除并返回一个任意的(键
值)对。
Remove and return an arbitrary (key, value) pair from the dictionary.
对于我的问题,假设我有一个字典(例如):
For my problem, suppose I have a dictionary like (an example):
>>> d = dict(zip((string.ascii_lowercase), range(1, 10)))
>>> d
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8}
现在我需要从中删除一些项目count由用户指定)
Now I need to remove some items from it (the count is specified by the user).
所以我写了:
>>> for _ in range(4): # assume 4 items have to removed
... d.popitem()
...
('a', 1)
('c', 3)
('b', 2)
('e', 5)
但是,这个代码的问题是,每次运行脚本时, popitem()
弹出相同的项目。你可以自由地测试一下,我已经尝试了多次。
But the problem with this code is, every time the script is run, popitem()
pops exactly the same items. You are free to test this, I have already tried it multiple times.
所以我的问题是:
- 为什么不是
popitem()
应该怎么办?删除任意项目不是随机的? - 如何从字典中删除随机项目?
- Why isn't
popitem()
working the way it should? Is removing arbitrary items not random? - How do I remove random items from a dictionary?
推荐答案
这是你在说什么?
import random
for i in range(4):
some_dict.pop( random.choice(some_dict.keys()) )
这篇关于从字典中随机删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!