简体   繁体   English

在python的for循环中附加附件

[英]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. 在这里,在方括号中,它存在增量点“ [m + 1]”,但在python中的“ for循环”中无法正常工作。 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) lst = []对于xrange(0,5,1)中的m:rs = [0,0,0,3] rg = range(5)lst.append(rg [m + 1],如果rs == 0或rg [m + 1]> 3否则0)

While, here, in square brackets, it does not exist the incremental point "[m]" but it is working properly the "for loop" in python. 虽然在方括号中,它不存在增量点“ [m]”,但在python中的“ for循环”中正常工作。

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! 因此,您可能有一个if内联语句,多数情况下,右侧是TRUE,但左侧可能仍然存在问题!

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. 例如,这将始终验证右边的部分,结果为0,但永远不会验证左边的部分。

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

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

m will go from 0 to 4. m从0到4。

rg has 5 elements with indexes 0 to 4. rg有5个元素,索引为0到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 . m为4时,您尝试将rg[m+1]附加到lst (取决于条件),这将尝试访问超出范围的rg[5] ,因为rg没有这样的索引。

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

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

The condition rg[m]>3 is True if m = 4 . 如果m = 4则条件rg[m]>3True So you have lst.append(rg[4+1]) . 因此,您拥有lst.append(rg[4+1]) rg[5] is out of range of rg rg[5]超出rg范围

P/S: How can you check rs == 0 while rs=[0,0,0,3] ? P / S:当rs=[0,0,0,3]时,如何检查rs == 0 It returns always False 它总是返回False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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