【问题标题】:how to separate list with the length of nested list python?如何将列表与嵌套列表python的长度分开?
【发布时间】:2020-03-16 07:03:01
【问题描述】:

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

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

任何建议都会有所帮助!

【问题讨论】:

  • 你已经尝试了什么?

标签: python python-3.x list nested-lists


【解决方案1】:

你需要:

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

【讨论】:

    【解决方案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']]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-30
      相关资源
      最近更新 更多