HumanTorch
HumanTorch

Reputation: 359

Python: How to find out if an unknown element exists in a list?

zero_crossings2 basically detects sign changes. If there is a zero_crossings2 I want to append 1 to crossing_list, otherwise I want to append a 0 to crossing_list. The code np.where(np.diff(np.sign(a2)))[0] can determine the index of the sign change. So if it returns a result I want to return a "1" at that specific position and a "0" everywhere it does not detect a sign change.

Here is the current state of my code:

import numpy as np
crossing_list = []
a2 = [1, 2, 1, 1, 0, -3, -4, 7, 8, 9, 10, -2, 1, -3, 5, 6, 7, -10]
zero_crossings2 = np.where(np.diff(np.sign(a2)))[0]


for i in range(len(a2)):
    if X in zero_crossings2[i]:
        crossing_list.append('1')
    else:
        crossing_list.append('0')

crossing_list_new = np.array(crossing_list)

What I am having trouble with is in the if-statement, the "X" is unknown so I do not know which element is in the list.

My expected output is:

[0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1]

Upvotes: 1

Views: 1118

Answers (1)

Axel Puig
Axel Puig

Reputation: 1334

To get the array you want, you can do:

a2 = [1, 2, 1, 1, 0, -3, -4, 7, 8, 9, 10, -2, 1, -3, 5, 6, 7, -10]
signs = np.sign(a2)
crossings = np.where(np.diff(signs), 1, 0)

The first zero is missing (because the first number of crossings corresponds to the crossing of the first and the second number of a2), so you can add it with this:

crossings = np.insert(crossings, 0, 0)

Upvotes: 5

Related Questions