简体   繁体   中英

Append enclosure in a for loop in python

I cannot understand why the append enclosure in square brackets do not work with an incremental point, but it works without the incremental point. It maybe, it gets out of bound ?

Here, in square brackets, it exists the incremental point "[m+1]" but it is not working properly the "for loop" in python. lst=[] for m in xrange(0,5,1): rs=[0,0,0,3] rg=range(5) lst.append(rg[m+1] if rs==0 or rg[m+1]>3 else 0)

While, here, in square brackets, it does not exist the incremental point "[m]" but it is working properly the "for loop" in python.

lst=[]
for m in xrange(0,5,1):
    rs=[0,0,0,3]
    rg=range(5)
    lst.append(rg[m+1] if rs==0 or rg[m]<3 else 0)

...and another example, by changing the direction of the sign "<" to ">". It is not working properly.

lst=[]
for m in xrange(0,5,1):
    rs=[0,0,0,3]
    rg=range(5)
    lst.append(rg[m+1] if rs==0 or rg[m]>3 else 0)

I found my answer!

an inline statement validate first the right part and then the left part. Left part of an inline statement can be erroneous stated until left part be validated. Therefore, you may have an if inline statement, that most of times, the right part is TRUE but the left part can remain faulty!

How can you check this? you must insert additional logical checks in that case? this is the only solution?

for example, this will always validate the right part, which will result 0, BUT never it will validate the left part.

r=[0,1]
a=[2,3]

r[99999] if a[1]==2 else 0

m will go from 0 to 4.

rg has 5 elements with indexes 0 to 4.

When m is 4 you try to append rg[m+1] to lst (depending on the condition), which would try to access rg[5] which is out of range, since there is no such index in rg .

for m in xrange(0,5,1) = for m in iter([0,1,2,3,4])

rg=range(5) = rg=[0,1,2,3,4]

The condition rg[m]>3 is True if m = 4 . So you have lst.append(rg[4+1]) . rg[5] is out of range of rg

P/S: How can you check rs == 0 while rs=[0,0,0,3] ? It returns always False

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