2016-03-03 20 views

回答

-1

算法

input = [2,5,1,4,7,3,1,2,3] 

output = [[]] 
for idx,val in enumerate(input): 
    if idx > 0 and input[idx-1] > input[idx]: 
     output.append([val]) 
    else: 
     output[-1].append(val) 

print output 

輸出爲

[[2, 5], [1, 4, 7], [3], [1, 2, 3]] 

文字的算法的說明:

與空子列表創建輸出列表。枚舉輸入列表。如果前一個元素(如果存在)不大於實際元素,則將該元素添加到輸出的最後一個子列表。如果它更大,請在輸出中創建一個新子列表並將其添加到此新子列表中。

+0

嗨Kordi請你解釋一下代碼 – SlickTester

+0

@ParagGhodaskar加了算法的解釋。你明白嗎? – Kordi

+0

是kordi.I正在嘗試使用冒泡排序,2> 5,5> 1 false,因此請從原始列表中刪除2,5並繼續排序剩餘的列表。我們可以這樣做嗎? – SlickTester

0

另一種解決方案:

def sortedsublist(): 
'''create sorted sublist from the given list''' 
    inputl = [] 
    sortedl = [] 
    subl = [] 
    inputl = [7,8,9,2,3,1,2,3,1,2,1] 
    for i in range(len(inputl)): 
    try: 
    if inputl[i] <= inputl[i+1]: 
     subl.append(inputl[i]) 
    else: 
     subl.append(inputl[i]) 
     sortedl.append(subl) 
     subl= []  
    except IndexError: 
     subl.append(inputl[i]) 
     sortedl.append(subl) 
     subl = [] 
    print sortedl 
    return 
if __name__="main": 
    sortedsublist()