(编辑:jimmy 日期: 2024/12/31 浏览:2)
有些时候我们需要从视频序列中均匀的随机采样,我们可以每隔x步进行一次采样,这就要求对一个list每隔x步进行一次截取,再从截取到的不同的子集中随机选取一个数就是我们平均采样的帧的idx。
import random def split(a, n): k, m = divmod(len(a), n) return [a[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in list(range(n))] list_split = split(list(range(15)), 3) print(list_split) tmp = [random.choice(i) for i in list_split] print(tmp)
结果:
list_split====>
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]tmp====>
[0, 6, 12]
python list 平均 分割 等分
应用场景:根据线程数,分割任务列表;
####功能:将list对象N等分 def div_list(ls,n): if not isinstance(ls,list) or not isinstance(n,int): return [] ls_len = len(ls) if n<=0 or 0==ls_len: return [] if n > ls_len: return [] elif n == ls_len: return [[i] for i in ls] else: j = ls_len/n k = ls_len%n ### j,j,j,...(前面有n-1个j),j+k #步长j,次数n-1 ls_return = [] for i in xrange(0,(n-1)*j,j): ls_return.append(ls[i:i+j]) #算上末尾的j+k ls_return.append(ls[(n-1)*j:]) return ls_return if 0: print div_list(3,3) print div_list([3],'3') print div_list([3],-1) print div_list([],2) print div_list([3],2) print div_list([3,4,5,6],4) print div_list([3,4,5,6,7,8,9,10,11,12,13,14,15],3)