【问题标题】:fast way to uniformly remove 10% of all the elements in a given list of python统一删除给定 python 列表中所有元素的 10% 的快速方法
【发布时间】:2015-03-10 22:45:17
【问题描述】:

这个问题有两个方面。首先,据我了解,从给定列表中统一删除 10% 的想法如下所示。 (1): 计算 10% * totul 元素个数 (2):随机均匀地一个一个移除元素,直到列表中的元素个数最多为90%*totul元素个数 即,

while (the current number of elements is bigger than 90% * totul number of elements)
            randomly and uniformly generate an element from the current list and remove it.

上面说的对吗?这听起来更像没有替换吗?或者我可以使用任何内置的python函数。 其次,点击这个链接,Very fast sampling from a set with fixed number of elements in python 我的想法是从 python 的列表中删除元素是昂贵的。那么,有没有更好的方法来解决这个问题?非常感谢。

【问题讨论】:

  • 统一是什么意思?
  • 表示每个元素被选中的概率相同。

标签: python


【解决方案1】:

看来random.sample 是要走的路……

n_elements = int(len(elements) * 0.9)
randomly_selected = random.sample(elements, n_elements)

这通过创建一个新列表来解决“在 python 中从列表中删除元素代价高昂”的问题。

【讨论】:

    【解决方案2】:

    我通过获取列表的 90% 的大小来做到这一点,random.shuffleing 列表,然后重新分配列表从开始到 n(列表的 90%)。

    n = int(len(elements) * 0.9)
    random.shuffle(elements)
    elements = elements[:n]
    

    【讨论】:

      猜你喜欢
      • 2015-11-02
      • 1970-01-01
      • 2013-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-27
      相关资源
      最近更新 更多