两个给定数字之间等距的元素

Pra*_*pta 1 python

我正在处理视频文件。我有一个起始帧号。x(比如说 10)和一个停止帧号。y(比如 200)。我想在 x 和 y 之间拾取“n”帧(比如 n=8)。这些“n”个帧应该是唯一的并且在 x 和 y 之间等距

请建议在 Python 3.x 中执行此操作的最快方法。目前我正在使用这个:

list = random.sample(range(start_frame,stop_frame), int((stop_frame-start_frame)/n))
Run Code Online (Sandbox Code Playgroud)

这给了我独特的框架,但不是等距的。如何在开始和停止帧号之间获得等距的帧。

jpp*_*jpp 5

如果您愿意使用第三方库,则可以使用 NumPy。您可以使用numpy.linspace将范围均分为n 个分量:

import numpy as np

frames = np.linspace(10, 200, num=8)

print(frames)

[ 10.          37.14285714  64.28571429  91.42857143 118.57142857
 145.71428571 172.85714286 200.        ]
Run Code Online (Sandbox Code Playgroud)

如果需要整数,可以转换为int

print(frames.astype(int))

array([ 10,  37,  64,  91, 118, 145, 172, 200])
Run Code Online (Sandbox Code Playgroud)


Bra*_*mon 5

如果您希望两个端点都包含在内,您可以使用这样的方法从 10 到 200获得n=8帧:

x = 10
y = 200
n = 8
step = (y - x) / (n - 1)

frames = [x + step * i for i in range(n)]

print(frames)
[10.0, 37.14285714285714, 64.28571428571428, 91.42857142857143,
 118.57142857142857, 145.71428571428572, 172.85714285714286, 200.0]
Run Code Online (Sandbox Code Playgroud)