给定一个整数数组,我想确定值递增的不同整数组的数目。
给定数组myList = [1, 2, 3, 4, 3, 2, 2, 3, 1, 2, 1, 4, 2]
有4组不同的整数,其中值上升。即[1, 2, 3, 4], [2, 2, 3], [1, 2]
和[2]
有经验的人能指导我如何在python中实现这一点吗?
最佳答案
有一种方法:
group = []
list_of_groups = []
myList = [1, 2, 3, 4, 3, 2, 2, 3, 1, 2, 1, 4, 2]
for i in range(len(myList)):
if i == len(myList)-1:
if len(group) > 0:
group.append(myList[i])
list_of_groups.append(group)
else:
if myList[i] <= myList[i+1]:
group.append(myList[i])
else:
group.append(myList[i])
if len(group) > 1:
list_of_groups.append(group)
group = []
print(list_of_groups)
不同测试用例的结果-
myList = [1, 2, 3, 4, 3, 2, 2, 3, 1, 2, 1, 4, 2]
Output: [[1, 2, 3, 4], [2, 2, 3], [1, 2], [1, 4]
myList = [1, 2, 3, 4, 3, 2, 2, 3, 1, 2, 1, 4, 5]
Output: [[1, 2, 3, 4], [2, 2, 3], [1, 2], [1, 4, 5]]
myList = [1, 2]
Output: [[1, 2]]
myList = [1, 2, 3, 4]
Output: [[1, 2, 3, 4]]
myList = [5, 2, 3, 4]
Output: [[2, 3, 4]]
myList = [5, 2]
Output: []
关于python - 不同的整数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57236885/