我用随机的方法来整理列表。我需要按一定百分比随机化序列。例如,list是[1,2,3,4,5],我将列表随机播放十次,我希望第一个元素是2的百分比为50%,第二个元素是1的百分比为30%,依此类推。 / p>
谢谢
答案 0 :(得分:0)
让我们尝试以下一种情况:将数字置于索引0的可能性为50%:
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
30%同样如此... 您将需要更大的比例来说明更多的粒度值
例如31%或71.6,例如:len(scale)== 100,len(scale)== 1000。
答案 1 :(得分:0)
尝试使用以下代码:
>>> 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%
>>>