Python – Group Consecutive elements by Sign

PythonServer Side ProgrammingProgramming

When it is required to group consecutive elements by sign, the ‘^’ operator and the simple iteration along with ‘enumerate’ is used.

Below is a demonstration of the same −

Example

 Live Demo

my_list = [15, -33, 12, 64, 36, -12, -31, -17, -49, 12, 43, 30, -23, -35, 53]

print("The list is :")
print(my_list)

my_result = [[]]
for (index, element) in enumerate(my_list):

   if element ^ my_list[index - 1] < 0:
      my_result.append([element])
   else:
      my_result[-1].append(element)

print("The result is :")
print(my_result)

Output

The list is :
[15, -33, 12, 64, 36, -12, -31, -17, -49, 12, 43, 30, -23, -35, 53]
The result is :
[[15], [-33], [12, 64, 36], [-12, -31, -17, -49], [12, 43, 30], [-23, -35], [53]]

Explanation

  • A list is defined and is displayed on the console.

  • An empty list of list is defined.

  • The list is iterated using ‘enumerate’, and the ‘^’ operator is used to check if the specific element is less than 0.

  • If yes, it is appended to the empty list.

  • Otherwise, it is appended to the end of the list.

  • This is displayed as the output on the console.

raja
Published on 04-Sep-2021 11:06:54
Advertisements