简体   繁体   中英

assign looping result to a variable in python

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

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]

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]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM