如果您不关心输入列表的顺序,我会对其进行洗牌,然后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
其中是和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]