推荐学习书目
› 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
saximi
V2EX  ›  Python

请问 append 和 extend 的区别在哪里?

  •  
  •   saximi · Aug 16, 2017 · 2912 views
    This topic created in 3329 days ago, the information mentioned may be changed or developed.
    下面的命令中,append 会出错,但是 extend 没有问题,请问两种方法的区别何在呢?

    >>> C=bytearray(b'xYam')

    >>> C.append(b'LMN')
    TypeError: an integer is required

    >>> C.extend(b'MNO')

    >>> C
    bytearray(b'xYamLMNO')
    3 replies  •  2017-08-17 05:57:27 +08:00
    7sDream
        1
    7sDream  
       Aug 17, 2017
    你可以理解成

    [1, 2, 3].append(4) = [1, 2, 3, 4]
    [1, 2, 3].append([4]) = [1, 2, 3, [4]] // 或者报错,如果是 bytes 必须要求每个元素是一个整数
    [1, 2, 3].extend([4]) = [1, 2, 3, 4]
    [1, 2, 3].extend([4]) = Error 因为 4 不可迭代
    zhengzhou1992
        2
    zhengzhou1992  
       Aug 17, 2017   ❤️ 1
    追加一个和追加一坨的区别
    siteshen
        3
    siteshen  
       Aug 17, 2017
    可以用 `help(xxx)` 或者 `print(xxx.__doc__)`,示例:


    $ python -c 'print(bytearray().extend.__doc__)'
    B.extend(iterable int) -> None

    Append all the elements from the iterator or sequence to the
    end of B.


    $ python -c 'print(bytearray().append.__doc__)'
    B.append(int) -> None

    Append a single item to the end of B.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5299 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 01:42 · PVG 09:42 · LAX 18:42 · JFK 21:42
    ♥ Do have faith in what you're doing.