First of all, I`m sorry if I might ask this question and if it was already answered somewhere else. I couldnt find any solution for the following Problem:
I want to create a list where I apply multiple restricions. But instead of using over hundreads of if statements i just want to use a dictionary in one if statement to apply the requirements. So to say I want to use the keys of the dictionary as requirements and its values as factors for the data.
Lets take a look at a small example:
I want to create data for a countourplot where x/y range from [-50,50] in steps of 1 and the z function has requirements based on the if statements:
The following code is what works, but the more requirements I add the longer and more unreadalbe the code gets:
x = np.linspace(-50 , 50, 100)
y = np.linspace(-50 , 50, 100)
z = []
z_0 = 100
for i in x:
for j in y:
if i**2 j**2 <= 10**2:
z.append(1.9 * z_0)
elif i**2 j**2 <= 20**2:
z.append(1.5 * z_0)
elif i**2 j**2 <= 30**2:
z.append(1.4 * z_0)
elif i**2 j**2 <= 40**2:
z.append(1.05 * z_0)
else
z.append(z_0)
This would create a map with radial decreasing hight as a function of z on different positions. Is it possible to do this in the following way which is way less redundant? My main problem is how to assing the correct value.
x = np.linspace(-50 , 50, 100)
y = np.linspace(-50 , 50, 100)
z = []
requirements_dict = {10:1,9, 20:1.5, 30:1.4, 40:1.05}
z_0 = 100
for i in x:
for j in y:
if i**2 j**2 <= (each key of the requirements_dict) :
z.append( (corresponding value of the requirements dict) * z_0)
else
z.append(z_0)
Thanks in advance for the help and sorry again if this question was already asked.
CodePudding user response:
Is this what you're looking for?
EDIT:
import numpy as np
x = np.linspace(-50 , 50, 100)
y = np.linspace(-50 , 50, 100)
z = []
requirements_dict = {10: 1.9, 20: 1.5, 30: 1.4, 40: 1.05}
z_0 = 100
for i in x:
for j in y:
for key, value in requirements_dict.items():
if i**2 j**2 <= key:
z.append(value * z_0)
break
else:
z.append(z_0)