Python Forum

Full Version: Loop over an an array of array
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have an array of arrays I want to loop over to return two arrays called hills and valleys. When looping through each element, we check the item at index 1 that is element[0] if the value is equal to zero, we create another array and push the value inside. we keep a trace of it still when we meet another element where the element[0] is greater than zero then the trace breaks after that we push what is in the array to the valley array and the same thing goes for hills.
Here is an example

arr = [[0.0, 1564.0], [0.0, 1565.0], [0.0, 1566.0], [0.0, 1567.0], [0.0, 1568.0], [0.0, 1569.0], [0.0, 1570.0], [7.18, 1571.0], [0.0, 1572.0], [0.0, 1573.0], [7.33, 1574.0], [0.0, 1575.0], [0.0, 1576.0], [7.18, 1577.0], [0.0, 1578.0], [0.0, 1579.0], [0.0, 1580.0], [0.0, 1581.0], [12.28, 1582.0], [0.0, 1583.0], [4.26, 1584.0], [0.0, 1585.0]] 

should return hills [
[7.18, 1571.0],
 [7.33, 1574.0], 
 [7.18, 1577.0],
 [4.26, 1584.0]
] and

 valleys should be [
[[0.0, 1564.0], [0.0, 1565.0], [0.0, 1566.0], [0.0, 1567.0], [0.0, 1568.0], [0.0, 1569.0], [0.0, 1570.0]],
[[0.0, 1572.0], [0.0, 1573.0]], 
[[0.0, 1575.0], [0.0, 1576.0]], 
[[0.0, 1578.0], [0.0, 1579.0], [0.0, 1580.0], [0.0, 1581.0]], 
[[0.0, 1583.0]],
[[0.0, 1585.0]]
].

Here is what I have done so far 

def plot_curve_with_annotation(input_array):

    hills = []
    valleys = []

    for element in input_array:
        value = element[0]
        
        if value == 0.0 or value == None:
         valleys.append(element)
        elif value > 0.0:
         hills.append(element)

    return hills, valleys

hills, valleys = plot_curve_with_annotation(arr)
print("Hills:", len(hills))
print("Valleys:", len(valleys))
Do you have a question? Your code appears to do what you want.