【问题标题】:Python repeatedly randomly deleting list entriesPython反复随机删除列表条目
【发布时间】:2014-09-19 17:59:32
【问题描述】:

我正在尝试从 Python 中的列表列表中随机删除一个列表。它一直给我错误:

IndexError: list assignment index out of range

如果我从 0 -> len(thelist) 中删除一个随机整数,我不明白我是如何引用列表中某处的。

我想随机删除列表的一半(例如/ 12个成员中随机删除其中6个)

for j in range(length/2):
    dynamiclength = len(sorted_population_list)
    del sorted_population_list[random.randint(0, dynamiclength)]

【问题讨论】:

    标签: python list random indexing


    【解决方案1】:

    这是因为random.randint 也可以返回端点值,因此当返回值等于len(sorted_population_list) 时,您将得到IndexError

    解决方法是使用不包括端点的random.randrange

    请注意,对于更大的列表,最好创建一个新列表(并在需要时将其重新分配回相同的变量)而不是使用del,因为它是一个O(N) 操作,所以对于每次删除你'正在执行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
    • @jonrsharpe 是的!正在更新我的答案,但我的连接被拉断了。
    猜你喜欢
    • 1970-01-01
    • 2017-12-24
    • 2012-03-20
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-09
    • 1970-01-01
    相关资源
    最近更新 更多