python - 通过分组从 python 中的列表列表创建新列表

标签 python

这个问题与我的另一个问题相关: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]。

感谢大家的快速回复! :)

最佳答案

ziplist 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/

相关文章:

Python redis 根据时间戳获取列表

python - 在 Python Pandas 中将数据帧/列归零的最快方法

python - graphlab-sframe : How to remove rows which have same ids and condition on a column?

python - 如何使用 jupyter notebook 在网格中显示多个 png

python - 计算引擎的服务帐户没有足够的云视觉 API 范围

python - 如何在 Python 的二维数组中查找值的索引?

python - 如何注释将 AnyStr 设为 str 默认值的函数?

python - 如何在 Pandas 的数据框上使用 Excel 内置格式(会计格式)

python - 无法理解在源代码中查找何处以创建网络抓取工具

python - 属性错误 : 'function' object has no attribute 'func_name' and python 3