Python Matching Lists Length

I have two Python lists of different lengths. It can be assumed that one of the lists is several times larger than the other.

Both lists contain the same physical data, but with different sampling frequencies.

My goal is to reduce the size of the larger signal so that it has exactly as many data points as there are less.

I came up with the following code that basically does this work, but not very pythonic and not able to handle very large lists in its own 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

I would appreciate it if more experienced Python users could develop alternative ways to solve this problem.

Any response or comment is greatly appreciated.

+4
4

( ):

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 , "" , :

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

-, numpy. numpy, , , , numpy

import numpy as np
a = np.array(a)
b = np.array(b)

. len , array.shape , ( ) .

 a[::a.shape[0] // b.shape[0]]

, . a b ( 10e6 1e6 ) , numpy .

a = np.ones(10000000)
b = np.ones(1000000)

%timeit a[::a.shape[0] // b.shape[0]]  # Numpy arrays
1000000 loops, best of 3: 348 ns per loop

a = list(a); 
b = list(b);
%timeit a[::len(a) // len(b)]    # Plain old python lists
1000000 loops, best of 3: 29.5 ms per loop
+1

, , .

from __future__ import division

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

def zip_downsample(a, b):
    if len(a) > len(b):
        b, a = a, b  # make b the longer list
    for i in xrange(len(a)):
        yield a[i], b[i * len(b) // len(a)]

for z in zip_downsample(a, b):
    print z
0
#a = [1,2,3,4,5,6,7,8,9,10]
#b = [1,4.5,6.9]

a, b = zip(*zip(a, b))

# a = [1, 2, 3]
# b = [1, 4.5, 6.9]

zip , , - [(1, 1), (2, 4.5), (3, 6.9)]. zip ( *), zip, . [a, b], (a, b = ...).

https://www.programiz.com/python-programming/methods/built-in/zip zip ,

-1

Source: https://habr.com/ru/post/1684764/


All Articles