拉伸列表以适合彼此的尺寸

时间:2018-07-24 21:41:55

标签: python numpy sequence

说我有3个大小不匹配的列表,[3, 7, 6], [12, 67, 89, 98], and [1, 2, 3, 4, 5, 6, 7] 我想要一个函数来做到这一点:

>>> stretch([3, 7, 6], [12, 67, 89, 2], [1, 2, 3, 4, 5, 6, 7])
[3, 3, 3, 7, 7, 6, 6], [12, 67, 67, 89, 89, 2, 2], [1, 2, 3, 4, 5, 6, 7]

所以,我想要的是将所有较小的列表拉伸到最大列表的长度。如果有2个最大的大小相等的列表,请保留它们的相同长度。我尝试使用一个函数,但仅使用范围有效。我希望它可以处理所有问题。这里供参考:

import numpy

def zipstretch(*args):
        range_tups = [(x[0], x[-1]) for x in args]
        shifts = [x[0] for x in range_tups]
        range_tups = [(x[0]-y, x[1]-y, n) for x, y in zip(range_tups, shifts)]
        ranges = []
        for x, s in zip(range_tups, shifts):
            h = s
            temp = list()
            for y in range(max(range_tups, key=lambda z: len(z))[0], max(range_tups, key=lambda z: len(z))[1]):
                temp.append(h)
                h+=x[1]/max(range_tups, key=lambda z: len(z))[1]
            ranges.append(numpy.array(temp))
        return ranges

2 个答案:

答案 0 :(得分:3)

我想到了这个

def stretch(*lists):
    length = max([len(l) for l in lists])
    return [[l[i * len(l) // length] for i in range(length)]
            for l in lists]

它将目标长度计算为所有列表的最大值,然后根据它们的索引拉伸列表,这与您实现幼稚的一维图像缩放的方式类似。

答案 1 :(得分:0)

不是超级Pythonic,Florian的答案要好得多,但是无论如何我都想发布答案。

def stretch(*lists):
    max_len = max([len(l) for l in lists])
    stretched = []
    for l in lists:
        init_factor = factor = (max_len - 1) / len(l)
        new_l = []
        i = 0
        j = 1
        while j <= max_len:
            new_l.append(l[i])
            if j > factor:
                i += 1
                factor += init_factor
            j += 1
        stretched.append(new_l)
    return stretched

stretch([3, 7, 6], [12, 67, 89, 2], [1, 2, 3, 4, 5, 6, 7])
# => [[3, 3, 3, 7, 7, 6, 6], [12, 12, 67, 67, 89, 2, 2], [1, 2, 3, 4, 5, 6, 7]]