Python - 按符号对连续元素进行分组
给定一个基于符号的连续元素的列表组。
Input : test_list = [5, -3, 2, 4, 6, -2, -1, -7, -9, 2, 3]
Output : [[5], [-3], [2, 4, 6], [-2, -1, -7, -9], [2, 3]]
Explanation : Elements inserted into new list on sign change.
Input : test_list = [-2,3,4,5,6,-3]
Output : [[-2], [3, 4, 5, 6], [-3]]
Explanation : Elements inserted into new list on sign change.
方法#1:使用循环
在这种情况下,每当发生符号(正或负)变化时,都会启动一个新列表,否则元素将附加到与初始化类似的列表中。
Python3
# Python3 code to demonstrate working of
# Group Consecutive elements by Sign
# Using loop
# initializing list
test_list = [5, -3, 2, 4, 6, -2, -1, -7,
-9, 2, 3, 10, -3, -5, 3]
# printing original list
print("The original list is : " + str(test_list))
res = [[]]
for (idx, ele) in enumerate(test_list):
# checking for similar signs by XOR
if ele ^ test_list[idx - 1] < 0:
res.append([ele])
else:
res[-1].append(ele)
# printing result
print("Elements after sign grouping : " + str(res))
Python3
# Python3 code to demonstrate working of
# Group Consecutive elements by Sign
# Using groupby() + list comprehension
import itertools
# initializing list
test_list = [-2, 3, 4, 5, 6, -3]
# printing original list
print("The original list is : " + str(test_list))
# grouped using groupby()
res = [list(ele) for idx, ele in itertools.groupby(test_list, lambda a: a > 0)]
# printing result
print("Elements after sign grouping : " + str(res))
输出:
The original list is : [5, -3, 2, 4, 6, -2, -1, -7, -9, 2, 3, 10, -3, -5, 3]
Elements after sign grouping : [[5], [-3], [2, 4, 6], [-2, -1, -7, -9], [2, 3, 10], [-3, -5], [3]]
方法 #2:使用 groupby() + 列表理解
在此,我们使用 groupby() 执行分组任务,并使用列表理解来执行遍历列表的任务。符号的条件是使用 lambda函数注入的。
蟒蛇3
# Python3 code to demonstrate working of
# Group Consecutive elements by Sign
# Using groupby() + list comprehension
import itertools
# initializing list
test_list = [-2, 3, 4, 5, 6, -3]
# printing original list
print("The original list is : " + str(test_list))
# grouped using groupby()
res = [list(ele) for idx, ele in itertools.groupby(test_list, lambda a: a > 0)]
# printing result
print("Elements after sign grouping : " + str(res))
输出:
The original list is : [-2, 3, 4, 5, 6, -3]
Elements after sign grouping : [[-2], [3, 4, 5, 6], [-3]]