Python重复随机删除列表项

Python重复随机删除列表项,python,list,random,indexing,Python,List,Random,Indexing,我试图从Python中的列表列表中随机删除一个列表。它不断地给我错误: IndexError: list assignment index out of range 如果我从0->len(列表)中删除一个随机整数,我不明白我是如何引用列表中的某个地方的 我想随机删除列表的一半(前/共12名成员随机删除其中6名) 这是因为您还可以返回端点值,因此当返回值等于len(排序的\u population\u list)时,您将得到索引器 修复方法是使用不包括端点的 请注意,对于较大的列表,最好创建一个

我试图从Python中的列表列表中随机删除一个列表。它不断地给我错误:

IndexError: list assignment index out of range
如果我从0->len(列表)中删除一个随机整数,我不明白我是如何引用列表中的某个地方的

我想随机删除列表的一半(前/共12名成员随机删除其中6名)

这是因为您还可以返回端点值,因此当返回值等于
len(排序的\u population\u list)
时,您将得到
索引器

修复方法是使用不包括端点的

请注意,对于较大的列表,最好创建一个新列表(如果需要,将其重新分配回同一个变量),而不是使用
del
,因为它是一个操作,所以每次删除都要执行
O(N)
操作

首先,我从
xrange
中选择一个长度等于列表长度的大小为
n
的随机样本,然后使用列表理解过滤掉这些索引

def remove_items(lst, n):
    indices = set(random.sample(xrange(len(lst)), n))
    lst[:] = [x for i, x in enumerate(lst) if i not in indices]
lst = range(12)
remove_items(lst, 4)
print lst  #[1, 3, 7, 8, 9, 10] 

值得一提的是,最简单的修复方法是切换到
randrange
@jornsharpe-Yup!正在更新我的答案,但我的连接被拉断了。
def remove_items(lst, n):
    indices = set(random.sample(xrange(len(lst)), n))
    lst[:] = [x for i, x in enumerate(lst) if i not in indices]
lst = range(12)
remove_items(lst, 4)
print lst  #[1, 3, 7, 8, 9, 10]