如何将列表列入列表?

时间:2015-03-15 21:02:41

标签: python

如何从下面显示的“列表”中获取项目,看起来像每个列表中具有相同数量项目的“new_list”

list  = [1,0,1,1,1,0,1,0,          new_list = [[1,0,1,1,1,0,1,0],
         0,0,0,1,1,0,0,0,                      [0,0,0,1,1,0,0,0],
         1,1,1,0,0,1,0,0,                      [1,1,1,0,0,1,0,0],
         0,0,0,0,0,1,1,1]              `       [0,0,0,0,0,1,1,1]]

1 个答案:

答案 0 :(得分:3)

您可以使用slicing

>>> l= [1,0,1,1,1,0,1,0,          
...     0,0,0,1,1,0,0,0,                      
...     1,1,1,0,0,1,0,0,                      
...     0,0,0,0,0,1,1,1] 

>>> [l[i:i+8] for i in range(0,len(l),8)]
[[1, 0, 1, 1, 1, 0, 1, 0], 
 [0, 0, 0, 1, 1, 0, 0, 0], 
 [1, 1, 1, 0, 0, 1, 0, 0], 
 [0, 0, 0, 0, 0, 1, 1, 1]]

检查子列表中的连续1:

>>> new=[l[i:i+8] for i in range(0,len(l),8)]
>>> [all(i==1 for i in sub) for sub in new]
[False, False, False, False]
>>> new.append([1,1,1,1,1,1,1])
>>> [all(i==1 for i in sub) for sub in new]
[False, False, False, False, True]