Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 给定一个长度为x的列表,重复该操作以获得长度为n的列表_Python_List - Fatal编程技术网

Python 给定一个长度为x的列表,重复该操作以获得长度为n的列表

Python 给定一个长度为x的列表,重复该操作以获得长度为n的列表,python,list,Python,List,我有一个列表,如下所示 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],

我有一个列表,如下所示

    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]]]
我现在可以使用chain将列表列表上传到列表列表列表中

    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是3的倍数。如果我想重复它20次或17次,20/3=6.666667,重复函数的第二个参数需要是一个整数。如果我了解您想要做什么,您希望能够得到任意长度的列表,而不仅仅是输入的倍数。以下内容将为您提供一种动态方式,以获得您想要的结果

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

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]

你具体想达到什么目标?为几个例子提供您的输入和预期输出,因为您目前拥有的不足以理解您的最终目标。请参阅如何提供。我更喜欢
itertools.islice(itertools.chain(*s),所需金额)
。它的效率更高(因为它不会强制其他值进入列表)。事实上,你的
列表中的大多数调用都是不必要的。这很有意义。我将原始版本与islice进行了比较,两者大致相同。初始值为227µs±9.74µs/环,而初始值为237µs±10.6µs/环。您的新更新实际上每个循环返回237µs±6.51µs。这都是边缘值,因此任何一种方法都是正确的。对于初学者来说,我的原创可能更容易理解到底发生了什么:)呃,它在错误条内。在
list of\u list
所需金额
的大值下,效率低下的地方更明显!我想你的答案是更有效的。