[英]Algorithm for removing entries from an array, by removing “middlest” items?
Given a list of items of length n
, where a maximum number of wanted items is m
, and m < n
, and in which the items in the list which are most valuable / useful are those that are furthest from any other item. 给定一个长度为
n
的项目列表,其中所需的最大项目数为m
,且m < n
,并且列表中最有价值/最有用的项目是距离其他项目最远的项目。 How can I remove items from the list to reduce the size of the list to m
. 如何从列表中删除项目以将列表的大小减小为
m
。
eg, for [ a, b, c, d, e ]
with an m == 2
, we would get [ a, e]
例如,对于
m == 2
[ a, b, c, d, e ]
,我们将得到[ a, e]
eg, for [ a, b, c, d, e ]
with an m == 3
, we would get [ a, c, e ]
例如,对于
m == 3
[ a, b, c, d, e ]
,我们将得到[ a, c, e ]
[ a, b, c, d, e ]
with an m == 4
, we would get [ a, b, c, e ]
or [ a, c, d, e ]
. m == 4
[ a, b, c, d, e ]
,我们将得到[ a, b, c, e ]
或[ a, c, d, e ]
。 (Either answer would be valid; but only one should be returned, and preferably it would be deterministically returned.) Note: I am generalizing a real problem, which is selecting representative frames from a video. 注意:我正在推广一个实际的问题,那就是从视频中选择代表性的帧。 The code will be written in python.
该代码将用python编写。
Step through the list with steps of about size (n-1)/(m-1)
, where "about" is there because we can't land on a non-integer. 用大约大小
(n-1)/(m-1)
步长逐步浏览列表,其中存在“大约”是因为我们不能使用非整数。
def representatives(l, m):
num, den = len(l)-1, m-1
return [l[i * num // den] for i in range(m)]
Here, element i
of the result is taken from element i*(n-1)//(m-1)
of the input, where //
is floor division. 在此,元件
i
的结果的从元件中取出i*(n-1)//(m-1)
的输入的,其中, //
是地板分裂。
For a collection c
: 对于集合
c
:
sparse_list = c[::len(c)//(m-1)]
This returns a list with a step size of len(c)//(m-1)
(note integer division). 这将返回一个步长为
len(c)//(m-1)
(注意整数除法)。
eg: 例如:
c = list(range(50))
m = 5
c[::len(c)//(m-1)] # [0, 12, 24, 36, 48]
It's not quite perfect because it goes for exact spacing, but it's quick and easy (and performant). 它不是很完美,因为它需要精确的间距,但是它又快速又容易(且性能出色)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.