简体   繁体   English

逗号后跟变量赋值如何连接?

[英]How does a comma followed by a variable assignment concatenate?

I am still in the early stages of learning Python and came accross this syntax but I have no idea what it does. 我仍处于学习Python的早期阶段,并且遇到了这种语法,但是我不知道它的作用。

check, expression = expression, expression.replace('()', '').replace('[]', '').replace('{}', '')

Now I know what the str.replace() function does, I am just unclear in how in the end is "check" being assigned to this concatenation of replace functions. 现在,我知道str.replace()函数的功能了,但是我到底不清楚如何将“检查”分配给这组替换函数。

Context: 内容:

Here is the full code for context, the purpose of it is just to check wether brackets are being used correctly in a given string: 这是上下文的完整代码,其目的只是检查给定字符串中是否正确使用了括号:

BRACKETS = ("{","[","(","}","]",")")
list = []

#Creating a list with only the brackets in it.
for c in expression:
    if (c in BRACKETS) and (c in expression):
        list.append(c)

expression = ''.join(list)

while expression:
    check, expression = expression, expression.replace('()', '').replace('[]', '').replace('{}', '')
    if expression == check:
        return False
return True

The line you're asking about is equivalent to: 您要询问的行等于:

check      = expression
expression = expression.replace('()', '').replace('[]', '').replace('{}', '')

Python allows multiple assignments with a single = . Python允许使用一个=进行多个分配。 Each variable on the left side is assigned a corresponding value from the right side. 左侧的每个变量都从右侧分配了相应的值。

Consider the following example: 考虑以下示例:

a = 'a'
b = 'b'

temp = a
a = b
b = temp

print(a) # 'b'
print(b) # 'a'

From this, it can be seen that the three lines in the middle swap the values of a and b . 由此可见,中间的三行交换ab的值。 In Python, tuple packing and unpacking can be used in order to eliminate the need for the temporary variable. 在Python中,可以使用元组打包和拆包以消除对临时变量的需要。

a = 'a'
b = 'b'

temp_tuple = b, a # tuple packing
print(temp_tuple) # ('b', 'a')

a, b = temp_tuple # tuple unpacking
print(a) # 'b'
print(b) # 'a'

Now, we can combine this packing and unpacking into a single expression. 现在,我们可以将打包和拆包合并为一个表达式。

a = 'a'
b = 'b'

a, b = b, a

print(a) # 'b'
print(b) # 'a'

You code saves the original value of expression into check and saves the updated version of expression back into expression . 你的代码保存的原始值expressioncheck并保存的更新版本expressionexpression It then compares the two variables to see whether expression was changed by all the replace calls. 然后,它将两个变量进行比较,以查看是否所有replace调用都更改了expression

Edit: Regarding the comment about whether Python goes through the code segment three times, we can use to dis module to disassemble the Python bytecode for a test function. 编辑:关于Python是否经过3次代码段的注释,我们可以使用dis模块来分解测试功能的Python字节码。

from dis import dis

def test(expression):
    while expression:
        check, expression = expression, expression.replace('()', '').replace('[]', '').replace('{}', '')
        if expression == check:
            return False
    return True

print dis(test)

This prints the following (with some annotations): 这将打印以下内容(带有一些注释):

# while expression:
4           0 SETUP_LOOP              75 (to 78)
      >>    3 LOAD_FAST                0 (expression)   # start
            6 POP_JUMP_IF_FALSE       77                # jump to exit

# check, expression = [...]
5           9 LOAD_FAST                0 (expression)
           12 LOAD_FAST                0 (expression)
           15 LOAD_ATTR                0 (replace)
           18 LOAD_CONST               1 ('()')
           21 LOAD_CONST               2 ('')
           24 CALL_FUNCTION            2
           27 LOAD_ATTR                0 (replace)
           30 LOAD_CONST               3 ('[]')
           33 LOAD_CONST               2 ('')
           36 CALL_FUNCTION            2
           39 LOAD_ATTR                0 (replace)
           42 LOAD_CONST               4 ('{}')
           45 LOAD_CONST               2 ('')
           48 CALL_FUNCTION            2
           51 ROT_TWO             
           52 STORE_FAST               1 (check)
           55 STORE_FAST               0 (expression)

# if check == expression:
6          58 LOAD_FAST                0 (expression)
           61 LOAD_FAST                1 (check)
           64 COMPARE_OP               2 (==)
           67 POP_JUMP_IF_FALSE        3                # jump to start

# return False
7          70 LOAD_GLOBAL              1 (False)
           73 RETURN_VALUE        
           74 JUMP_ABSOLUTE            3                # jump to start
      >>   77 POP_BLOCK                                 # exit

# return True
8     >>   78 LOAD_GLOBAL              2 (True)
           81 RETURN_VALUE        

From this it can be seen that the following occurs: 从中可以看出发生了以下情况:

  1. expression is loaded and checked for its truthiness. 加载expression并检查其真实性。 If True , the loop immediately exits. 如果为True ,则循环立即退出。
  2. The values of check and expression are loaded, updated, swapped, and stored. checkexpression的值将被加载,更新,交换和存储。
  3. The value of check is compared to that of expression . check的值与expression的值进行比较。 If False , the loop jumps to the start. 如果为False ,则循环跳至起点。 Otherwise, False is returned. 否则,返回False
  4. The value of True is returned. 返回True的值。 This will only occur if the loop exited because the value of expression was not truthy in the first step. 仅在循环退出时才会发生这种情况,因为第一步中expression的值不正确。

I think that the only real thing to note in the check, expression = [...] line is the use of the instruction ROT_TWO , which swaps the two top-most stack items. 我认为,在check, expression = [...]唯一要注意的问题是check, expression = [...]行,它使用了指令ROT_TWO ,该指令交换了两个最顶层的堆栈项。 On line 9, the value of expression is loaded. 在第9行,将加载expression的值。 On lines 12-48, the value of expression loaded and updated, pushing the value loaded on line 9 back in the stack. 在第12-48行中, expression的值已加载和更新,将第9行中加载的值推回堆栈中。 Then, on line 51, these two values are swapped. 然后,在第51行,交换这两个值。

Explanation 说明

For example: 例如:

x, y = 1, 2

x will be initialized with 1 & y be initialized with 2. x将以1初始化, y将以2初始化。

You can also use this to unwrap tuples. 您还可以使用它来展开元组。 For eg 例如

>>> def foo(): return 1, 2
>>> x = foo()
>>> x  # It is tuple
(1, 2)   
>>> x, y = foo()  # Value of 'x' is 1 and 'y' is 2
>>> x
1
>>> y
2

You can also use this to swap two numbers as a, b = b, a 您还可以使用它交换两个数字,例如a, b = b, a

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

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