创建数字列表列表。如果排序错误,则应创建一个新的子列表
Create list of list of numbers. If sorting is wrong a new sublist should be created
a) 输入是数字列表
i/p = > [2,5,1,4,7,3,1,2,3]
b) 输出应该是排序的子列表
o/p = > [[2,5],[1,4,7],[3],[1,2,3]]
算法
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]]
算法文字解释:
创建一个带有空子列表的输出列表。枚举输入列表。如果前一个元素(如果存在)不大于实际元素,则将元素添加到输出的最后一个子列表。如果它更大,则在输出中创建一个新的子列表并将其添加到这个新的子列表中。
另一个解决方案:
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()
a) 输入是数字列表
i/p = > [2,5,1,4,7,3,1,2,3]
b) 输出应该是排序的子列表
o/p = > [[2,5],[1,4,7],[3],[1,2,3]]
算法
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]]
算法文字解释:
创建一个带有空子列表的输出列表。枚举输入列表。如果前一个元素(如果存在)不大于实际元素,则将元素添加到输出的最后一个子列表。如果它更大,则在输出中创建一个新的子列表并将其添加到这个新的子列表中。
另一个解决方案:
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()