<分区>
我正在尝试将括号放入列表中。这是代码:
list_1 = [1,2,2]
list_2 = [1,2,3,4,5]
我想使用“list_1”中的数字将“list_2”放在括号中。像这样:
[[1],[2,3],[4,5]]
我如何使用 Python 3 实现此目的?
标签 python python-3.x list
<分区>
我正在尝试将括号放入列表中。这是代码:
list_1 = [1,2,2]
list_2 = [1,2,3,4,5]
我想使用“list_1”中的数字将“list_2”放在括号中。像这样:
[[1],[2,3],[4,5]]
我如何使用 Python 3 实现此目的?
最佳答案
这是一种使用 iter
ator 的方法进行更改。
list_1 = [1,2,2]
list_2 = [1,2,3,4,5]
it = iter(list_2)
res = []
for take in list_1:
res.append([next(it) for _ in range(take)])
print(res) # -> [[1], [2, 3], [4, 5]]
当然,也存在列表理解版本1:.
it = iter(list_2)
res = [[next(it) for _ in range(take)] for take in list_1]
最后,正如@Chris_Rands 在下面的评论中指出的那样,您可以使用 islice
来自非常有用的 itertools
模块。它负责上面代码的迭代器创建部分,因此更加紧凑。
import itertools
res = [list(itertools.islice(list_2, take)) for take in list_1]
print(res) # -> [[1], [2, 3], [4, 5]]
============================================= ===========================
1 记得重新创建迭代器!
关于python - 如何在 Python 3 中相应地将括号放入列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50904470/