这个问题与我的另一个问题相关:silence out regions of audio based on a list of time stamps , using sox and python
如果q= [[0.0,4.0], [10.0,12.0], [15.0,20.0], [21.0,28.0], [32.0,36.0],[41.0,44.0]]
新列表 q' 应为 [4.0,10.0],[12.0,15.0],[20.0,21.0],[28.0,32.0], [36.0,41.0]]
我所做的如下:
import numpy
q= [[0.0,4.0], [10.0,12.0], [15.0,20.0], [21.0,28.0], [32.0,36.0],[41.0,44.0]]
x= []
print "in between"
for t in range(len(q)-1):
a,b=q[t][1],q[t+1][0]
x.append([a,b])
for i in x:
print i
输出:
[4.0, 10.0]
[12.0, 15.0]
[20.0, 21.0]
[28.0, 32.0]
[36.0, 41.0]
更新:我想在我的 ^ 输出中附加两个片段。
上下文:这些片段是时间戳。
假设这些段不是从 0 开始,而是从 3.0 开始
q= [[3.0,4.0], [10.0,12.0], [15.0,20.0], [21.0,28.0], [32.0,36.0],[41.0,44.0]]
文件以 50.0 结尾。
对于我的原始输出,我想添加区域:[0.0,3]
和[44.0,50.0]
这样我也可以消除这些区域。
为此我只是做了:
import numpy
speaker_segments= [[3.0,4.0], [10.0,12.0], [15.0,20.0], [21.0,28.0], [32.0,36.0],[41.0,44.0]]
segments_to_silence = []
starting= 0.0
end= 50.0
# simple output
for t in range(len(speaker_segments)-1):
a, b = speaker_segments[t][1],speaker_segments[t+1][0]
segments_to_silence.append([a, b])
val = len(speaker_segments)
y= speaker_segments[val-1][1]
# appending end of segment item and end of file item to output i.e [44.0,50.0].
if end >y:
a,b =y,end
segments_to_silence.append([a,b])
print "appending end regions"
print segments_to_silence
# appending the starting portions 0.0 - 3.0 :
f=speaker_segments[0][0]
if starting < f:
a=starting
b=f
segments_to_silence.append([a,b])
print "appending beginning regions"
print segments_to_silence
输出:
appending end regions:
[[4.0, 10.0], [12.0, 15.0], [20.0, 21.0], [28.0, 32.0], [36.0, 41.0], [44.0, 50.0]]
appending beginning regions:
[[4.0, 10.0], [12.0, 15.0], [20.0, 21.0], [28.0, 32.0], [36.0, 41.0], [44.0, 50.0], [0.0, 3.0]]
是否可以将附加的[0.0,3.0]移动到开头?这样它们就按时间顺序排列在排序列表中?
更新2: 我只需重新排序 if 条件,以便 [0.0,x.x] 首先出现,然后是中间,最后是文件末尾 [50.0]。
感谢大家的快速回复! :)
最佳答案
与 zip
和 list comprehension您可以执行以下操作:
x = [[a[1], b[0]] for a, b in zip(q, q[1:])]
由于您使用的是 python 2,因此最好使用 zip
的迭代器版本:itertools.izip
from itertools import izip
x = [[a[1], b[0]] for a, b in izip(q, q[1:])]
编辑:使用 itertools.islice
正如让-弗朗索瓦在评论中指出的那样:
from itertools import islice, izip
x = [[a[1], b[0]] for a, b in izip(q, islice(q, 1, None))]
关于python - 通过分组从 python 中的列表列表创建新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48208216/