l = [1,2,3,4,5]
# To store newly sorted list
result = []
#say I want a 50% chance for some number to shuffle into result[0]
#make a list that scales to 100.. im using 10 for this example.
scale = [i for i in range(10)]
print(scale)
#make a 'random' selection from this scale
placement = random.choice(scale)
# since a random choice has an equal chance of landing on either half of the scale,
# your effective probability of this happening is 50%
if placement <5:
result.append(1)
else:
#do something else
>>> import random
>>> l=[1,2,3,4,5]
>>> l2=[random.sample(l,len(l)) for i in range(10)]
>>> print('\n'.join([('Index %s. %s appears %s'%(idx,max(i,key=i.count),int((max([i.count(x) for x in i])/len(i))*100)))+'%' for idx,i in enumerate(zip(*l2))]))
Index 0. 2 appears 30%
Index 1. 2 appears 30%
Index 2. 4 appears 50%
Index 3. 3 appears 30%
Index 4. 3 appears 40%
>>>
让我们用一个例子来试试这个:50%的概率一个数字被放在索引0处:
30%也是如此。。。 您将需要更大的比例来考虑更细粒度的值
例如31%或71.6,例如:len(scale)==100,len(scale)==1000。你知道吗
尝试使用以下代码:
相关问题 更多 >
编程相关推荐