我是 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
其中 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]
关于python - 是否可以从列表中随机*删除*一定百分比/数量的项目,然后将它们*附加*到另一个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16847597/