我有一个dictionary:键是字符串,值是浮点数.
例:
A = {'a':1, 'b':2, 'c':2, 'd':0}
Run Code Online (Sandbox Code Playgroud)
我想以相同的概率获得'b'或'c'作为答案.我找到了一种获得所述行为的方法.但是我不相信这是最好的做法.
import random
A = {'a':1, 'b':2, 'c':2, 'd':0}
all = (A.items())
values = [(x[1],random.random(),x[0]) for x in all]
maxIndex = values.index(max(values))
print(values[maxIndex][2])
Run Code Online (Sandbox Code Playgroud)
有更好的(甚至更优雅的)方法吗?