2015-12-31 56 views
1

我想在條件基礎上從一個列表中創建多個列表。如何從python中的一個列表中創建多個列表

實際數據:

numbers = [1, 2, 3,4,5,6,7,8,9, 1, 11, 12, 13, 1, 21, 22, 25, 6, 1, 34 ,5 ,6 ,7,78] 

預期成果:

[1, 2, 3,4,5,6,7,8,9] 
[1, 11, 12, 13] 
[1, 21, 22, 25, 6] 
[1, 34 ,5 ,6 ,7,78] 

這裏是我的嘗試:

list_number=[] 
numbers = [1, 2, 3,4,5,6,7,8,9, 1, 11, 12, 13, 1, 21, 22, 25, 6, 1, 34 ,5 ,6 ,7,78] 
for x in numbers: 
    if x==1: 
     list_number.append(numbers) 

print list_number[0] 
+1

發佈您的嘗試.. –

+0

您到目前爲止嘗試了什麼? –

+1

'1'是一個分隔符,還是有一些其他的邏輯在工作? – TigerhawkT3

回答

5

而不是增加新的引用/原始numbers副本到list ,無論你何時看到,都要開始新的list一個1或添加到最新版本,否則:

list_number = [] 
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 11, 12, 13, 1, 21, 22, 25, 6, 1, 34, 5, 6, 7, 78] 
for x in numbers: 
    if x==1: 
     list_number.append([1]) 
    else: 
     list_number[-1].append(x) 

print list_number 

結果:

>>> for x in list_number: 
...  print x 
... 
[1, 2, 3, 4, 5, 6, 7, 8, 9] 
[1, 11, 12, 13] 
[1, 21, 22, 25, 6] 
[1, 34, 5, 6, 7, 78] 
0

我的建議是2步進,先找到那些的索引,然後從一個打印到其他和最後到最後:

ones_index=[] 
numbers = [1, 2, 3,4,5,6,7,8,9, 1, 11, 12, 13, 1, 21, 22, 25, 6, 1, 34 ,5 ,6 ,7,78] 
for i,x in enumerate(numbers): 
    if x==1: 
     ones_index.append(i) 

for i1,i in enumerate(ones_index): 
    try: 
     print numbers[i:ones_index[i1+1]] 
    except: 
     print numbers[i:] 
相關問題