Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying a list while iterating when programming with python [duplicate]

A program I'm using at work uses Python as a scripting language. I am perplexed in my attempts to modify a list while interating over it. Also, I have some logic inside the for loop that I would like to convert portions of the list from floats to text. In the end all the text have to be exactly 4 spaces. In my research to solve this problem I have come accross numerous simular problems for other people attempting to modify a list while iterating over it. However I feel my issue is unique because I am attempting to modify the list from floats to text while iterating over it.

I actually found a work around for the problem but I feel the solution was more complicated then it needed to be and I'm looking for a more simple solution which is the reason why I'm here. I would like to improve the code.

Here is the code which is giving me problems:

#these come in as floats with a single decimal space, ex:99.9
val = [AvailibilityLine1, AvailibilityLine2,
       PerformanceLine1, PerformanceLine2,
       QualityLine1, QualityLine2]

for i in val:
    j = 0
    if i >= 100:
       val[j] = "100 "                                                           
    elif i >= 10 and i < 100:
       val[j] = str(val)
    elif i > 0 and  i < 10:
       val[j] = " " + str(val)
    elif i <= 0:
       val[j] = "    "    #insert 4 spaces
    else:
       val[j] = "    "    #insert 4 spaces if all else fails
    j=j+1
like image 494
ForgottenKahz Avatar asked Sep 26 '26 16:09

ForgottenKahz


1 Answers

you can access and change the list value using index following way:

val= [1,2,3,4,5,6,50,110]
for i in xrange(len(val)):
    if val[i] >= 100:
       val[i] = "100 "                                                           
    elif val[i] >= 10 and val[i] < 100:
       val[i] = str(val[i])
    elif val[i] > 0 and  val[i] < 10:
       val[i] = " " + str(val[i])
    elif val[i] <= 0:
       val[i] = "    "    #insert 4 spaces
    else:
       val[i] = "    "    #insert 4 spaces if all else fails

print val
like image 75
venpa Avatar answered Sep 29 '26 11:09

venpa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!