[英]Run same loop twice, but getting different results
I cannot figure this out, but say I have a depth-3 array of strings called "text". 我无法弄清楚,但是说我有一个称为“文本”的深度为3的字符串数组。
How can it be that in the following code: 在下面的代码中怎么可能这样:
print "FIRST"
for gate in text[1:]:
print "GATE"
for text in gate:
print "TEXT"
for entry in text:
print "ENTRY"
print what
print "SECOND"
for gate in text[1:]:
print "GATE"
for text in gate:
print "TEXT"
for entry in text:
print "ENTRY"
print what
I get different output for each loop. 每个循环得到不同的输出。
"First" “第一”
FIRST
GATE
TEXT
ENTRY
א
ENTRY
מחברת אל"ף
ENTRY
אחל לבאר לשון יהודית, להעמיד כל מלה כפי שאת, יש מלה רבת פנים ולא יתבונן המשכיל יסודותיה, כי אם במהות ענינה אשר סביבותיה למרבית פניה, כי המלה מושכת והולכת עד אשר מתחלקת ממראה אחד עד חמשה עשר פנים, על כן יש מלה אשר הענין ימשכנה ויורה עליה וילמד על גזרתה. ויש מלה אשר היא מושכת הענין ומבארת הפתרון ושכל סודו, וכה הוא פתרון הלשון ופשר המלים לפי מחלקותיהם ותוצאותיהם.
TEXT
ENTRY
אב.
"Second" “第二”
SECOND
GATE
TEXT
ENTRY
מ
TEXT
ENTRY
ת
TEXT
ENTRY
ח
TEXT
ENTRY
ל
TEXT
ENTRY
Each Loop is coded exactly the same and yet I get different output. 每个循环的编码都完全相同,但是我得到的输出却不同。 How is this possible? 这怎么可能?
for
loops "leak" variables. for
循环的“泄漏”变量。 You might expect gate
, text
, and entry
to be scoped to their respective loops, but they're actually global. 您可能希望gate
, text
和entry
作用域是它们各自的循环,但是它们实际上是全局的。 So, at the end of this loop 因此,在此循环结束时
for text in gate:
The value of text
has been altered, which affects the next loop. text
的值已更改,这会影响下一个循环。
Here's a more minimal example: 这是一个更简单的示例:
x = 'abc'
for x in x:
print x,
# output: "a b c"
for x in x:
print x,
# output: "c"
(If being able to run the same code twice and get the same result is the kind of thing that you find valuable, Python might not be the right choice of language for you. There are plenty of lovely languages that do have this property.) (如果能够两次运行相同的代码并获得相同的结果是您认为有价值的事情,那么Python可能不是您的正确语言选择。很多可爱的语言都具有此属性。)
text
has been modified. text
已被修改。 Before the SECOND loop, text
has its value taken from the last iteration of for text in gate: ...
在SECOND循环之前, text
的值取自for text in gate: ...
You should consider renaming the inner loop variable to something different. 您应该考虑将内部循环变量重命名为其他名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.