首页 > 解决方案 > 给定一个长度为 x 的列表,重复它以获得长度为 n 的列表

问题描述

我有一个列表,如下所示。

    f = [[1],[10,3], [10,15,16,20]]

我想重复这个列表一定次数。假设我希望最终列表的长度为 12。我可以执行以下操作,

    from itertools import repeat, chain 

    s = list(repeat(f, 4))

这给了我

    [[[1], [10, 3], [10, 15, 16, 20]],
    [[1], [10, 3], [10, 15, 16, 20]],
    [[1], [10, 3], [10, 15, 16, 20]],
    [[1], [10, 3], [10, 15, 16, 20]]]

我现在可以使用链将列表列表升级到列表列表中

    d = list(chain(*s))

d给出,

    [[1],
    [10, 3],
    [10, 15, 16, 20],
    [1],
   [10, 3],
   [10, 15, 16, 20],
   [1],
   [10, 3],
   [10, 15, 16, 20],
   [1],
   [10, 3],
   [10, 15, 16, 20]]

d 的长度是 12。但这可能只是因为 12 是三的倍数。如果我想重复 20 次或 17 , 20/3 = 6.666667 并且重复函数的第二个参数需要是整数怎么办。

标签: pythonlist

解决方案


如果我了解您想要做什么,您希望能够获得任意长度的列表列表,而不仅仅是您输入的倍数。下面应该给你一个动态的方式来获得你想要的结果。

它查看输入的长度并四舍五入到刚好高于所需数量的值。最后,它返回一个列表,其中仅包含您要查找的值的数量。

from itertools import chain, repeat, islice
import math

def my_func(list_of_lists, desired_amount):
     scalar = math.ceil(desired_amount/len(list_of_lists))
     s = repeat(list_of_lists, scalar)
     d = chain.from_iterable(s)
     return list(islice(d, desired_amount))

f = [[1],[10,3], [10,15,16,20]]
my_func(f, 20)
[[1],
 [10, 3],
 [10, 15, 16, 20],
 [1],
 [10, 3],
 [10, 15, 16, 20],
 [1],
 [10, 3],
 [10, 15, 16, 20],
 [1],
 [10, 3],
 [10, 15, 16, 20],
 [1],
 [10, 3],
 [10, 15, 16, 20],
 [1],
 [10, 3],
 [10, 15, 16, 20],
 [1],
 [10, 3]]

len(my_func(f, 20))
20

使用更简单语言的替代方法。

def my_func(list_of_lists, desired_amount):
     l = len(list_of_lists)
     multiplier = math.ceil(desired_amount/l)
     s = list(repeat(list_of_lists, multiplier))
     d = list(chain(*s))
     return d[:desired_amount]

推荐阅读