两个 Python 列表的匹配长度 [英] Match length of two Python lists

查看:99
本文介绍了两个 Python 列表的匹配长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个不同长度的 Python 列表.人们可能会假设其中一个列表比另一个大数倍.

I have two Python lists of different length. One may assume that one of the lists is multiple times larger than the other one.

两个列表都包含相同的物理数据,但以不同的采样率捕获.

Both lists contain the same physical data but captured with different sample rates.

我的目标是对较大的信号进行下采样,使其具有与较小信号完全一样多的数据点.

My goal is to downsample the larger signal such that it has exactly as much data points as the smaller one.

我想出了以下代码,它基本上完成了这项工作,但既不是 Pythonic 也不能以高性能的方式处理非常大的列表:

I came up with the following code which basically does the job but is neither very Pythonic nor capable of handling very large lists in a performant way:

import math

a = [1,2,3,4,5,6,7,8,9,10]
b = [1,4.5,6.9]

if len(a) > len(b):
    div = int(math.floor(len(a)/len(b)))
    a = a[::div]
    diff = len(a)-len(b)
    a = a[:-diff]
else:
    div = int(math.floor(len(b)/len(a)))
    b = b[::div]
    diff = len(b)-len(a)
    b = b[:-diff]
print a
print b

如果更有经验的 Python 用户能够详细说明解决此任务的替代方法,我将不胜感激.

I would appreciated if more experienced Python users could elaborate alternative ways to solve this task.

非常感谢任何回答或评论.

Any answer or comment is highly appreciated.

推荐答案

这是代码的缩短版本(不一定性能更好):

Here's a shortened version of the code (not necessarily better performance):

a = [1,2,3,4,5,6,7,8,9,10]
b = [1,4.5,6.9]
order = 0  # To determine a and b.

if len(b) > len(a):
    a, b = b, a  # swap the values so that 'a' is always larger.
    order = 1

div = len(a) / len(b)  # In Python2, this already gives the floor.
a = a[::div][:len(b)]

if order:
    print b
    print a
else:
    print a
    print b

由于您最终会丢弃较大列表的一些后面的元素,因此显式 for 循环可能会提高性能,因为这样您就不必跳转"到将被丢弃:

Since you're ultimately discarding some of the latter elements of the larger list, an explicit for loop may increase performance, as then you don't have to "jump" to the values which will be discarded:

new_a = []
jump = len(b)
index = 0
for i in range(jump):
    new_a.append(a[index])
    index += jump
a = new_a

这篇关于两个 Python 列表的匹配长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆