-2

Suppose I have an array a=[1.8 1.2 2.2 1.6]. I want to write a code so that I can get the smallest value till the values in the array are exhausted.

The desired output at the first step:

1.2

This value is then assigned to int_SOC and acts as an input for a while loop below:

fin_SOC = 3.2
i=0
    while True:
        if int_SOC < fin_SOC:
            int_SOC += output_params.iloc[i, 3]
        else:
            break
        
        i+=1
        print(int_SOC)

Only at the end of this while loop int_SOC should get the next smallest value that is in our case 1.6.

Here, output_params is a pandas time-series data frame.

As the next step, we are left with an array a=[1.8 2.2 1.6]. Now the desired output: 1.6 which is again assigned to int_SOC and while loop is again executed.

And so on...

Nick
  • 1
  • 4

2 Answers2

1

Well the first step of getting the values, smallest first can be achieved by just sorting the list:

a = [1.8, 1.2, 2.2, 1.6]
for item in sorted(a):
    print(item)

Output:

1.2
1.6
1.8
2.2
quamrana
  • 37,849
  • 12
  • 53
  • 71
  • What if I want to assign these sorted values to variables say `m`, `n`, `o`, `p` ? ie `m=1.2`, `n=1.6`, `o=1.8`,`p=2.2` – Nick Aug 29 '21 at 17:02
  • use: `dict(zip(list('mnop'), sorted(a)))` – mozway Aug 29 '21 at 17:06
  • @Nikhil: No, don't do that. – quamrana Aug 29 '21 at 17:09
  • @quamrana Any particular reason? – Nick Aug 29 '21 at 17:14
  • @Nikhil: Yes, [this](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) question has lots of answers. – quamrana Aug 29 '21 at 17:16
  • @quamrana: I am totally confused by reading these answers. I want to do it because each value has to go through a set of `if-else` conditions in the next steps. Also, the size of the array above is dynamic as the values are user input. Could you please suggest me a way out? – Nick Aug 29 '21 at 17:55
  • Yes, convert your code snippet into a function and then you'll be able to call it with each element of `sorted(a)`. – quamrana Aug 29 '21 at 17:57
1

Getting the values one after the other in order is called sorting ;)

Just use a builtin method for that:

a=[1.8, 1.2, 2.2, 1.6]
for value in sorted(a):
    print(value)

output:

1.2
1.6
1.8
2.2
mozway
  • 194,879
  • 13
  • 39
  • 75
  • Hell ya! I was so much into the next steps of my code I forgot the basics :D Thank you – Nick Aug 29 '21 at 16:35