Python - 在列表中将每个增加和减少的运行分组
给定一个列表,任务是编写一个Python程序来对每个递增和递减的运行进行分组。这被称为单调分组。如果列表是单调递增或单调递减,则列表是单调的。如果对于所有 i <= j,A[i] >= A[j],则列表 A 是单调递减的。
例子:
Input : test_list = [5, 6, 2, 9, 7, 1, 10, 4, 2, 1, 11, 12, 2]
Output : [[5, 6], [2], [9], [7, 1], [10], [4, 2, 1], [11, 12], [2]]
Explanation : 6 > 5 and then 2 is smaller than 6, hence becomes decreasing and new group is started. 2 and 9 being peak or transit elements, belong to individual groups.
Input : test_list = [5, 6, 2, 9, 7, 1, 10, 4, 2, 1]
Output : [[5, 6], [2], [9], [7, 1], [10], [4, 2, 1]]
Explanation : 6 > 5 and then 2 is smaller than 6, hence becomes decreasing and new group is started. 2 and 9 being peak or transit elements, belong to individual groups.
示例:使用循环+ zip()
在这种情况下,每两个列表都从第 0 个和第一个索引开始被压缩,然后比较两者中的每个元素以检查运行并相应地更改标志。初始标志值是根据前 2 个元素中的哪个更大来评估的,在切换该标志以具有适当的运行分组后。
Python3
# Python3 code to demonstrate working of
# Monotonous grouping in List
# Using loop + zip()
# initializing list
test_list = [5, 6, 2, 9, 7, 1, 10, 4, 2, 1, 11, 12, 2]
# printing original list
print("The original list is : " + str(test_list))
res = []
temp = []
is_up = True
if test_list[0] > test_list[1]:
is_up = False
for curr, nex in zip(test_list, test_list[1:]):
temp.append(curr)
# checking for increasing or decreasing to change list
if (nex > curr and not is_up) or (nex < curr and is_up):
res.append(temp)
temp = []
# toggling
is_up = not is_up
temp.append(nex)
res.append(temp)
# printing result
print("Monotonous grouping : " + str(res))
输出:
The original list is : [5, 6, 2, 9, 7, 1, 10, 4, 2, 1, 11, 12, 2]
Monotonous grouping : [[5, 6], [2], [9], [7, 1], [10], [4, 2, 1], [11, 12], [2]]