简体   繁体   English

以下for循环如何工作?

[英]How does the following for loop work?

def escape_html(s):
    for (i, o) in (("&","&amp;"),(">", "&gt;"),("<", "&lt"),('"', "&quot;")):
        s = s.replace(i , o)
    return s

I haven't seen something like this before. 我以前没见过这样的东西。

What does the first line of the for loop mean? for循环的第一行是什么意思?

In general, what does the loop do and how does it do it? 一般来说,循环是做什么的,它是如何做到的?

Note: s is a string 注意:s是一个字符串

Please try to explain the full iterative process. 请尝试解释完整的迭代过程。

In English: 用英语:

For each pair of values in the following list of pairs of values, do the stuff in the loop. 对于以下值对列表中的每对值,请在循环中执行这些操作。 In this case, (i, o) just means "Assign the values from the pair to variables named i & o." 在这种情况下,(i,o)只是意味着“将对中的值分配给名为i&o的变量”。

During the first iteration, i is "&" and o is "&amp;" 在第一次迭代期间, i是“&”而o是“&amp;”

Each time through the loop, it replaces occurrences of i with the replacement in o so any "&" in the source text becomes "&amp;", ">" becomes "&gt", etc. 每次循环时,它用o的替换替换i出现,因此源文本中的任何“&”变为“&amp;”,“>”变为“&gt”等。

This is pretty straight forward python. 这是非常直接的python。

The for loop is unpacking individual items from an iterable. for循环从可迭代中解包单个项目。 So, for example you could do someting like this: 所以,举个例子你可以这样做:

>>> c = [('a', 'b', 'c'), ('d', 'e', 'f')]
>>> for i, j, k in c:
...     print i, j, k
... 
a b c
d e f

In your case (i, o) are being populated with the values from the tuple of tuples. 在你的情况下(i, o)正在填充元组元组的值。 Instances of i are then replaced with the value of o . 然后将i实例替换为o的值。 This function is replacing html special characters with the entity representing each. 此函数正在用表示每个字符的实体替换html特殊字符。

>>> s = 'foo & bar'
>>> s = s.replace('&', '&amp;')
>>> s
'foo &amp; bar'

This function is equivalently doing: 这个函数等效地做:

def escape_html(s):
    s = s.replace("&","&amp;")
    s = s.replace(">", "&gt;")
    s = s.replace("<", "&lt")
    s = s.replace('"', "&quot;")
    return s

In lieu of using a proper debugger, try adding some print statements to see what is going on: 代替使用正确的调试器,尝试添加一些打印语句以查看发生了什么:

def escape_html(s):
    print "ORIGINAL STRING: %s" % (s)
    for (i, o) in (("&","&amp;"),(">", "&gt;"),("<", "&lt"),('"', "&quot;")):
        print "\t(i, o) = ('%s', '%s')" % (i, o)
        s = s.replace(i , o)
        print "\ts = %s" % (s, )
        print
    return s

mystring = """<h3>This is a test</h3><script>alert("I hacked you!");</script>"""
print escape_html(mystring)

OUTPUT OUTPUT

ORIGINAL STRING: <h3>This is a test</h3><script>alert("I hacked you!");</script>
    (i, o) = ('&', '&amp;')
    s = <h3>This is a test</h3><script>alert("I hacked you!");</script>

    (i, o) = ('>', '&gt;')
    s = <h3&gt;This is a test</h3&gt;<script&gt;alert("I hacked you!");</script&gt;

    (i, o) = ('<', '&lt')
    s = &lth3&gt;This is a test&lt/h3&gt;&ltscript&gt;alert("I hacked you!");&lt/script&gt;

    (i, o) = ('"', '&quot;')
    s = &lth3&gt;This is a test&lt/h3&gt;&ltscript&gt;alert(&quot;I hacked you!&quot;);&lt/script&gt;

&lth3&gt;This is a test&lt/h3&gt;&ltscript&gt;alert(&quot;I hacked you!&quot;);&lt/script&gt;

for每对物品的io in对序列(("&","&amp;"),(">", "&gt;"),("<", "&lt"),('"', "&quot;"))replace S的每个实例io在串s

for (i, o) in (("&","&amp;"),(">", "&gt;"),("<", "&lt"),('"', "&quot;")):

i and o are your loop variables. 我和o是你的循环变量。 & > < " are the characters to be replaced, and &amp; &gt; &lt; &quot; are the characters to replace them with. & > < "是要替换的字符, &amp; &gt; &lt; &quot;是要替换它们的字符。

In the first iteration of the loop i = & and o = &amp; 在循环的第一次迭代中, i = &o = &amp; In the second iteration i = > and o = &gt; 在第二次迭代中, i = >o = &gt; and so on. 等等。

The thing you're iterating over is a tuple of tuples (pairs in this case). 你迭代的东西是一个元组元组(在这种情况下是对)。

So for each iteration of the loop, i gets the first thing, and o gets the second. 所以对于循环的每次迭代,我得到第一个东西,而o得到第二个。 EG, on the first iteration, i gets & and o gets &. EG,在第一次迭代中,我得到&和o得到&。

So then it just keeps creating new strings with i replaced by o. 所以它只是继续创建新的字符串,用i代替。

consider that tuple as tupl =(("&","&amp;"),(">", "&gt;"),("<", "&lt"),('"', "&quot;")) to make it simpler. 将元组视为tupl =(("&","&amp;"),(">", "&gt;"),("<", "&lt"),('"', "&quot;"))使它更简单。

So the items of tupl are ("&","&amp;") , (">", "&gt;") , etc 所以tupl的项目是("&","&amp;")(">", "&gt;")等等

so the for loop becomes: 所以for循环变成:

  for (i,o) in tupl:

what it does is it fetches the items from the tupl one by one are tries to do something like : 它的作用是从tupl逐个获取项目尝试做类似的事情:

(i,o)=("&","&amp;") , or simply i,o=("&","&amp;") , which assigns the '&' to i and &amp; (i,o)=("&","&amp;") ,或简单地说i,o=("&","&amp;") ,它将'&'分配给i&amp; to o in the first iteration and > to i and &gt; 到第一次迭代中的o>i&gt; to o in second iteration, and so on. o在第二次迭代中,依此类推。

(("&","&amp;"),(">", "&gt;"),("<", "&lt"),('"', "&quot;")) are tuples in a tuple. (("&","&amp;"),(">", "&gt;"),("<", "&lt"),('"', "&quot;"))是元组中的元组。

Let's reduce it to simpler terms. 让我们把它简化为更简单的术语。

for (x, y) in ( ('a', 'b'), ('c', 'd') ):
    print x, y   

This prints the contents of each tuple... 这打印出每个元组的内容......

a, b
c, d

Perhaps that clears things up. 或许这可以解决问题。

(("&","&amp;"),(">", "&gt;"),("<", "&lt"),('"', "&quot;")) is a tuple with 4 elements in it. (("&","&amp;"),(">", "&gt;"),("<", "&lt"),('"', "&quot;"))是一个包含4个元素的元组在里面。

The element at index 0 is the tuple ("&","&amp;") 索引0处的元素是元组("&","&amp;")

When you say a, b = 0, 1 , python evaluates it the same as (a, b) = (0, 1) , where the variables are assigned corresponding values. 当你说a, b = 0, 1 ,python将它与(a, b) = (0, 1) ,其中变量被赋予相应的值。 That is, a takes the value 0 and b takes the value 1 . 也就是说, a取值0b取值1

Your for loop effectively loops over the big tuple with 4 elements in it. 你的for循环有效地遍历大元组,里面有4个元素。 Since each element is a 2-tuple, you are able to assign their respective values to the two variables i and o 由于每个元素都是2元组,因此您可以将它们各自的值分配给两个变量io

(("&","&amp;"),(">", "&gt;"),("<", "&lt"),('"', "&quot;")) is a 4-tuple with each element being a 2-tuple (for ex., ("&","&amp;") ). A tuple is a fixed-length sequence. You can read up more on them here: http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/loopsandtuples.html (("&","&amp;"),(">", "&gt;"),("<", "&lt"),('"', "&quot;"))是一个4元组每个元素都是一个2元组(例如, ("&","&amp;") )。元组是一个固定长度的序列。你可以在这里阅读更多信息: http://anh.cs。 luc.edu/python/hands-on/3.1/handsonHtml/loopsandtuples.html

The first line is just a for loop over the sequence. 第一行只是序列上的for循环。 The left hand side (before the 'in') takes advantage of python unpacking. 左侧(在'in'之前)利用python解包。 It takes the two values of a tuple and distributes them, one into i and the other into o . 它采用元组的两个值并将它们分配,一个进入i ,另一个进入o

In general, for each tuple the for loop replaces the first element of the tuple with the second. 通常,对于每个元组,for循环用第二个元素替换元组的第一个元素。

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

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