V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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
lts9165
V2EX  ›  Python

请教一个python赋值语句的问题

  •  
  •   lts9165 · Oct 8, 2013 · 3821 views
    This topic created in 4597 days ago, the information mentioned may be changed or developed.
    l = [1, 2, 3]
    a = [4]
    l[:] = a
    print l

    如上语句中, l[:] = a这句,算是什么类型的赋值呢?
    l[:]是个列表,如果这算是列表解包赋值,那右边的a又和l[:]的长度不一致
    求好心人指点迷津~~
    8 replies    1970-01-01 08:00:00 +08:00
    hanai
        1
    hanai  
       Oct 8, 2013   ❤️ 1
    hanai
        2
    hanai  
       Oct 8, 2013
    呃,错了。
    lts9165
        3
    lts9165  
    OP
       Oct 8, 2013
    @hanai 恩,好像确实有问题,l[:]和l确实是不同的对象,可是为什么能够直接给l[:]赋值呢
    lts9165
        4
    lts9165  
    OP
       Oct 8, 2013
    @hanai 我还试了[l[0],l[1],l[2]]=a 这样的赋值,就说a只有一个值,解不了
    vmebeh
        5
    vmebeh  
       Oct 8, 2013
    >>> i[:]==i
    True
    farseerfc
        6
    farseerfc  
       Oct 8, 2013   ❤️ 3
    區別用以下例子可以說清楚:
    >>> l = [1,2,3]
    >>> r = l
    >>> a = [4]
    >>> l
    [1, 2, 3]
    >>> r
    [1, 2, 3]
    >>> a
    [4]
    >>> l[:]=a
    >>> l
    [4]
    >>> r
    [4]
    >>> l = [1,2,3]
    >>> r = l
    >>> a = [4]
    >>> l = a
    >>> l
    [4]
    >>> r
    [1, 2, 3]
    >>> l = [1,2,3]
    >>> l[1:3] = a
    >>> l
    [1, 4]

    針對區段的賦值是可以替換整個區段的。
    lts9165
        7
    lts9165  
    OP
       Oct 8, 2013 via Android
    @farseerfc 哦!明白了!多谢~
    roricon
        8
    roricon  
       Oct 9, 2013
    我擦还能这么写,又学到了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1033 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 18:28 · PVG 02:28 · LAX 11:28 · JFK 14:28
    ♥ Do have faith in what you're doing.