Bee*_*ars 1 python random python-2.7
我是python和编程的新手,所以提前道歉.我知道remove(),append(),len()和rand.rang(或其他任何东西),我相信我需要这些工具,但我不清楚如何编写代码.
我想要做的是,在循环或以其他方式访问List_A时,随机选择List_A中的索引,从List_A中删除selected_index,然后将selected_index追加到List_B.
我想从列表A中随机删除最多一定百分比(如果不可能,则为实数).
有任何想法吗??我所描述的可能吗?
如果您不关心输入列表的顺序,我会将其随机播放,然后n从该列表中删除项目,将其添加到其他列表中:
from random import shuffle
def remove_percentage(list_a, percentage):
shuffle(list_a)
count = int(len(list_a) * percentage)
if not count: return [] # edge case, no elements removed
list_a[-count:], list_b = [], list_a[-count:]
return list_b
Run Code Online (Sandbox Code Playgroud)
其中percentage是0.0和之间的浮点值1.0.
演示:
>>> list_a = range(100)
>>> list_b = remove_percentage(list_a, 0.25)
>>> len(list_a), len(list_b)
(75, 25)
>>> list_b
[1, 94, 13, 81, 23, 84, 41, 92, 74, 82, 42, 28, 75, 33, 35, 62, 2, 58, 90, 52, 96, 68, 72, 73, 47]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1402 次 |
| 最近记录: |