V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2017-08-16 23:23:35 +08:00 · 2181 次点击
    这是一个创建于 2450 天前的主题,其中的信息可能已经有所发展或是发生改变。
    下面的命令中,append 会出错,但是 extend 没有问题,请问两种方法的区别何在呢?

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

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

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

    >>> C
    bytearray(b'xYamLMNO')
    3 条回复    2017-08-17 05:57:27 +08:00
    7sDream
        1
    7sDream  
       2017-08-17 00:04:39 +08:00
    你可以理解成

    [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  
       2017-08-17 00:14:50 +08:00   ❤️ 1
    追加一个和追加一坨的区别
    siteshen
        3
    siteshen  
       2017-08-17 05:57:27 +08:00
    可以用 `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.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   781 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 20:51 · PVG 04:51 · LAX 13:51 · JFK 16:51
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.