I am starting to learn python for a thesis project and here I am looking to get an output array using a conditional statement taking elements from 3 different arrays and need some guidance on how to approach this:
# I have 3 lists here with readings from a sensor:
summer = [92, 99, 86]
autumn = [91, 98, 82]
winter = [93, 96, 83]
# I want to perform this conditional statements on the arrays
# using the 1st element of each arrays, then the 2nd element
# and lastly the 3rd elements from each array:
if summer >= 90 and autumn >= 90 and winter >= 90:
a = 1
elif summer >= 90 and autumn >= 90 and winter >= 70:
a = 2
elif summer >= 50 and autumn >= 50 and winter >= 50:
a = 3
else:
a = 4
So in this example I am looking for a singular overall output of a = [1,1,3]
can anyone help with how I should approach this?
CodePudding user response:
Use a for
loop to iterate through the lists:
summer = [92, 99, 86]
autumn = [91, 98, 82]
winter = [93, 96, 83]
out = []
for s, a, w in zip(summer, autumn, winter):
if s >= 90 and a >= 90 and w >= 90:
out.append(1)
elif s >= 90 and a >= 90 and w >= 70:
out.append(2)
elif s >= 50 and a >= 50 and w >= 50:
out.append(3)
else:
out.append(4)
print(out) # [1, 1, 3]
CodePudding user response:
You could use indexing to access the contents of each array/list:
summer = [92,99,86]
autumn = [91,98,82]
winter = [93,96,83]
a = []
#range(3) since 3 is the length of each array
for i in range(3):
if summer[i]>=90 and autumn[i]>=90 and winter[i]>=90:
n=1
elif summer[i]>=90 and autumn[i]>=90 and winter[i]>=70:
n=2
elif summer[i]>=50 and autumn[i]>=50 and winter[i]>=50:
n=3
else:
n=4
a.append(n)
print(a)
CodePudding user response:
I prefer a "table driven" approach to this kind of problem rather than encumbering the logic with "magic" numbers. Something like this:
summer = [92, 99, 86]
autumn = [91, 98, 82]
winter = [93, 96, 83]
cv = [(90, 90, 90), (90, 90, 70), (50, 50, 50)]
av = []
for t in zip(summer, autumn, winter):
for i, c in enumerate(cv, 1):
if all(m >= n for m, n in zip(t, c)):
av.append(i)
break
else:
av.append(i 1)
print(av)
Output:
[1, 1, 3]
The advantage of this is that the core functionality doesn't change. You just need to change the lists (summer, autumn, winter & cv) appropriately