如何用嵌套列表的长度分隔列表?

2024-04-28 21:49:26 发布

您现在位置: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']]

任何建议都会有帮助


Tags: 元素home列表建议jpgshapecuts
2条回答

您可以将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']]

你需要:

c = []
count = 0
for i in a:
     c.append(b[count:count+len(i)])
     count = count+len(i)

print(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']]

相关问题 更多 >