我应该如何以一定的百分比排列一个列表?

2024-04-26 05:25:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我用random来洗牌。我需要按一定的百分比随机排列顺序。例如,list是[1,2,3,4,5],我将这个列表洗牌十次,我希望第一个元素是2,百分比为50%,第二个元素是1,百分比为30%,依此类推。你知道吗

谢谢


Tags: 元素列表顺序randomlist百分比
2条回答

让我们用一个例子来试试这个:50%的概率一个数字被放在索引0处:

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。你知道吗

尝试使用以下代码:

>>> 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%
>>> 

相关问题 更多 >