是否可以随机*删除*列表中的百分比/数量的项目&然后*将*附加到另一个列表?

时间:2013-05-30 23:40:01

标签: python python-2.7 random

我是python和编程的新手,所以提前道歉。我知道remove(),append(),len()和rand.rang(或其他任何东西),我相信我需要这些工具,但我不清楚如何编码。

我想做的是,在循环或以其他方式访问List_A时,随机选择List_A中的索引,从List_A中删除selected_index,然后将selected_index追加到List_B。

我想从列表A中随机删除最多某个百分比(如果不可能,则为实数)。

任何想法?我所描述的可能吗?

4 个答案:

答案 0 :(得分:8)

如果您不关心输入列表的顺序,我会将其随机播放,然后从该列表中删除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

其中percentage0.01.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]

答案 1 :(得分:1)

如果您可以在i中找到某个元素的随机索引listA,那么您可以使用以下方法轻松地将其从A移动到B

listB.append(listA.pop(i))

答案 2 :(得分:1)

1)计算要删除的元素数量,将其称为k

2)random.randrange(len(listA))将返回0到len(listA)-1之间的随机数,包括您可以在listA中使用的随机索引。

3)抓住该索引处的元素,将其从listA中删除,将其附加到listB。

4)重复,直到删除k个元素。

答案 3 :(得分:1)

>>> lis = range(100)
>>> per = .30 
>>> no_of_items = int( len(lis) * per) #number of items in 30 percent 
>>> lis_b = []
>>> for _ in xrange(no_of_items):
       ind = random.randint(0,len(lis)-1)  #selects a random index value
       lis_b.append(lis.pop(ind))     #pop the item at that index and append to lis_b 
...     
>>> lis_b
[73, 32, 82, 68, 90, 19, 3, 49, 21, 17, 30, 75, 1, 31, 80, 48, 38, 18, 99, 98, 4, 20, 33, 29, 66, 41, 64, 26, 77, 95]