小编典典

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

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]  

更新:我想在我的^输出中再添加两个段。

上下文:这些段是时间戳。

假设句段不是从零开始,而是从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,xx]首先出现,然后是文件[50.0]的中间,最后是结尾。

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


阅读 340

收藏
2021-01-20

共1个答案

小编典典

使用zip和列表理解,您可以执行以下操作:

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))]

您可以展平,丢弃第一个然后重新组合:

>>> 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]]
>>> from itertools import chain, islice
>>> list(map(list, zip(*2*(islice(chain(*q), 1, None),))))
[[4.0, 10.0], [12.0, 15.0], [20.0, 21.0], [28.0, 32.0], [36.0, 41.0]]

Python 2版本:

>>> from itertools import chain, islice, izip
>>> map(list, izip(*2*(islice(chain(*q), 1, None),)))
2021-01-20