wim*_*wim 6 python random dictionary
输入random.choice应该是一个序列。这会导致 a 出现奇怪的行为dict,它不是序列类型,但可以像下面这样使用下标:
>>> d = {0: 'spam', 1: 'eggs', 3: 'potato'}
>>> random.choice(d)
'spam'
>>> random.choice(d)
'eggs'
>>> random.choice(d)
'spam'
>>> random.choice(d)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/random.py", line 274, in choice
return seq[int(self.random() * len(seq))] # raises IndexError if seq is empty
KeyError: 2
Run Code Online (Sandbox Code Playgroud)
此外,random.choice它根本不适用于set和collections模块中的其他一些容器。
有充分的理由吗random.choice(d)不应该以明显的方式工作,返回随机密钥?
我考虑过random.choice(list(d)),random.sample(d, 1)[0]但希望有更有效的方法。可以random.choice在不降低序列当前行为的情况下进行改进吗?