How to do procedure in Pyhton Jupyter lab with a number list and not just with a list item

Asked

Viewed 28 times

0

I’m trying to do the procedure below but x and y are a list of numbers and that’s why it’s giving error. I used the following code:

theta = [180* math.atan(y/x)/math.pi for x,y in zip(media_v1, media_v2)] 

if x > 0 and y <0:
    theta = theta + 90
elif x < 0 and v < 0:
    theta = theta + 180
elif x < 0 and v > 0:
    theta = theta + 270

The first one I managed to do the procedure with the list (media_v1 and media_v2) all using the 'for', but when I try to do the 'if' it does not to the whole list and gives the following error:

TypeError: '>' not supported between instances of 'list' and 'int'

2 answers

0

I believe that the list comprehension will not help you in this, because of if. Use a normal structure of for

theta_list = []

for x,y in zip(media_v1, media_v2):
    theta = 180 * math.atan(y/x)/math.pi
    if x > 0 and y <0:
        theta = theta + 90
    elif x < 0 and y < 0:
        theta = theta + 180
    elif x < 0 and y > 0:
        theta = theta + 270

    theta_list.append(theta)

Then use the value of theta inside the iterating list. For example:

for t in theta_list:
    print(t)

0

You can separate the logic into a function and apply within the comprehensilist on as your IF applies to each iteration and not to the final result:

import math


def calculate_theta(x, y):
    t = 180 * math.atan(y/x) / math.pi
    if x > 0 and y <0:
        return t + 90
    elif x < 0 and y < 0:
        return t + 180
    elif x < 0 and y > 0:
        return t + 270
    else:
        return t


media_v1 = [1, 2, 3, 4, 5]
media_v2 = [4, 1, 5, 2, 3]


theta = [calculate_theta(x, y) for x, y in zip(media_v1, media_v2)]

Code running Repl.it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.