推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
shanghj
V2EX  ›  Python

Python 中 list[1],list[2]=list[2],list[1]的实现原理

  •  
  •   shanghj · Mar 10, 2019 · 3051 views
    This topic created in 2697 days ago, the information mentioned may be changed or developed.

    因为自己太笨了,实在想不通,所以来这里请教一下各位大佬。谢谢

    7 replies    2019-03-11 00:24:22 +08:00
    tdk1738
        1
    tdk1738  
       Mar 10, 2019
    闭包和拆包吧
    lance6716
        2
    lance6716  
       Mar 10, 2019 via Android
    rot_two
    wwqgtxx
        3
    wwqgtxx  
       Mar 10, 2019
    这种只要有个栈不是很好实现么
    push(list[2])
    push(list[1])
    list[2]=pop()
    list[1]=pop()
    binux
        4
    binux  
       Mar 10, 2019
    实现原理就是,Guido 想要 unpacking,于是就有了 unpacking
    inframe
        5
    inframe  
       Mar 10, 2019 via Android
    python 虚拟机是个完全的栈机
    shanghj
        6
    shanghj  
    OP
       Mar 10, 2019
    很感谢各位大佬的回复,实现原理已经了解。
    对于二楼的大佬的 ROT_TWO 的补充:
    #! /usr/bin/env python3
    # -*- coding:utf-8 -*-
    from dis import dis


    def demo(a, b):
    print(a,b)
    a, b = b, a
    print('new: ', a,b)


    a, b = 2, 3
    demo(a,b)
    dis(demo)
    ‘’‘
    输出结果:(重点在 ROT_TWO)
    2 3
    new: 3 2
    6 0 LOAD_GLOBAL 0 (print)
    2 LOAD_FAST 0 (a)
    4 LOAD_FAST 1 (b)
    6 CALL_FUNCTION 2
    8 POP_TOP

    7 10 LOAD_FAST 1 (b)
    12 LOAD_FAST 0 (a)
    14 ROT_TWO
    16 STORE_FAST 0 (a)
    18 STORE_FAST 1 (b)

    8 20 LOAD_GLOBAL 0 (print)
    22 LOAD_CONST 1 ('new: ')
    24 LOAD_FAST 0 (a)
    26 LOAD_FAST 1 (b)
    28 CALL_FUNCTION 3
    30 POP_TOP
    32 LOAD_CONST 0 (None)
    34 RETURN_VALUE
    ’‘’
    darkTianTian
        7
    darkTianTian  
       Mar 11, 2019
    你可以把右边想象成元组,
    左边实际应用了元组拆包
    `list[1], list[2] = (list[2], list[1])`
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   987 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 22:18 · PVG 06:18 · LAX 15:18 · JFK 18:18
    ♥ Do have faith in what you're doing.