python - 给定一个长度为 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 并且重复函数的第二个参数需要是整数怎么办。
解决方案
如果我了解您想要做什么,您希望能够获得任意长度的列表列表,而不仅仅是您输入的倍数。下面应该给你一个动态的方式来获得你想要的结果。
它查看输入的长度并四舍五入到刚好高于所需数量的值。最后,它返回一个列表,其中仅包含您要查找的值的数量。
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]
推荐阅读
- java - 线程“主”javax.crypto.BadPaddingException 中的异常:Java 中的解密错误
- android - 在 android Studio 中,如何以编程方式更改菜单项文本向右对齐?
- python - 如何让不和谐机器人创建频道
- reactjs - 在 React Next js 应用程序中单击链接时如何传递状态以打开第二个 Material UI 选项卡
- php - WooCommerce:为什么 `get_billing_first_name()` 返回全名?
- reactjs - 样式 MUI 文本字段占位符
- javascript - express.js 应用程序不显示控制台日志消息
- python - 如何使用 Xpath 抓取 Google 网址(包含和不包含)
- unity3d - 代码中的值更改时检查器不更新
- animation - 如何设置 Svelte + Popper.js + display:none 动画