please help me, I'm stuck to assign lopping output to a variable
here's my code
a = [0.5, 0.0, 1.2, 2.4, 0.1, 3.5]
for obs in a:
if obs > 0:
print('2')
elif obs < 0.1:
print('1')
the output is
2
1
2
2
2
2
I want to save that output in to a variable
CodePudding user response:
IIUC, store the result in the list 'b', as in below example
a = [0.5, 0.0, 1.2, 2.4, 0.1, 3.5]
b=[]
for obs in a:
if obs > 0:
b.append(2)
elif obs < 0.1:
b.append(1)
print(b)
[2, 1, 2, 2, 2, 2]
CodePudding user response:
You can create a variable out of the loop and save the value there or for a more "pythonic way" you can use list comprenhension
b = [1 if i <0.1 else 2 for i in a]
b is:
[2, 1, 2, 2, 2, 2]
CodePudding user response:
If I understand what you're trying to do correctly the easiest way would be to use another list and append the output to that list.
Something like this:
a = [0.5, 0.0, 1.2, 2.4, 0.1, 3.5]
#Output list that will be written to
output = []
for obs in a:
if obs > 0:
#Adds '2' to the end of the output list
output.append('2')
elif obs < 0.1:
#Adds '1' to the end of the output list
output.append('1')
#Loop to print the contents of output
for n in output:
print(n)
Output would be:
2
1
2
2
2
2