首页 > 解决方案 > 如何将列表与嵌套列表python的长度分开?

问题描述

我有一个这样的嵌套列表:

 a = [[0.00069053395], [0.7278625], [0.8591849, 0.86290157, 0.8703022], [0.9041279, 0.9102304, 0.91197634], [0.93096334, 0.93327045], [0.9456768, 0.95339334], [0.98164046, 0.9836741]]

和下面的另一个列表:

b = ['/home/shape/13.jpg', '/home/shape/5.jpg', '/home/shape/6.jpg', '/home/shape/0.jpg', '/home/shape/2.jpg', '/home/shape/1.jpg', '/home/shape/7.jpg', '/home/shape/11.jpg', '/home/cuts/shape/10.jpg', '/home/shape/4.jpg', '/home/shape/14.jpg', '/home/shape/12.jpg', '/home/shape/16.jpg', '/home/shape/8.jpg']

我想让列表b类似于嵌套列表a,其元素的长度。

预期输出:

c = [['/home/shape/13.jpg'],['/home/shape/5.jpg'],['/home/shape/6.jpg', '/home/shape/0.jpg', '/home/shape/2.jpg'],['/home/shape/1.jpg', '/home/shape/7.jpg', '/home/shape/11.jpg'],['/home/cuts/shape/10.jpg', '/home/shape/4.jpg'],['/home/shape/14.jpg', '/home/shape/12.jpg'],['/home/shape/16.jpg', '/home/shape/8.jpg']]

任何的意见都将会有帮助!

标签: pythonpython-3.xlistnested-lists

解决方案


您可以将iter内置函数与列表理解一起使用:

it = iter(b)

[[next(it) for _ in l] for l in a]

输出:

[['/home/shape/13.jpg'],
 ['/home/shape/5.jpg'],
 ['/home/shape/6.jpg', '/home/shape/0.jpg', '/home/shape/2.jpg'],
 ['/home/shape/1.jpg', '/home/shape/7.jpg', '/home/shape/11.jpg'],
 ['/home/cuts/shape/10.jpg', '/home/shape/4.jpg'],
 ['/home/shape/14.jpg', '/home/shape/12.jpg'],
 ['/home/shape/16.jpg', '/home/shape/8.jpg']]

推荐阅读