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
frmongo
V2EX  ›  Python

倒置 list

  •  
  •   frmongo · 2018-08-06 21:57:17 +08:00 · 2204 次点击
    这是一个创建于 2060 天前的主题,其中的信息可能已经有所发展或是发生改变。
    如果一个 list 的元素都是随机字符串,如何对 list 倒置,注意没有排序哦, 只是顺序换了?实现越短越好
    9 条回复    2018-08-07 10:21:57 +08:00
    ballshapesdsd
        1
    ballshapesdsd  
       2018-08-06 21:59:12 +08:00
    啥意思[::-1]不行么
    Yourshell
        2
    Yourshell  
       2018-08-06 22:02:00 +08:00 via iPhone
    list 不是有 reverse 方法吗
    twor
        3
    twor  
       2018-08-06 22:03:01 +08:00
    >>> a = [1,2,4,3,4]
    >>> a.reverse()
    >>> a
    [4, 3, 4, 2, 1]
    >>> list(reversed(a))
    [1, 2, 4, 3, 4]
    >>> a[::-1]
    [1, 2, 4, 3, 4]
    >>>
    neosfung
        4
    neosfung  
       2018-08-06 22:52:15 +08:00 via Android
    我觉得楼主说的是数据结构里的 list 吧
    xpresslink
        5
    xpresslink  
       2018-08-06 22:59:45 +08:00
    请楼使用人类易于易于理解的语言说明一下倒置代表的寒意。
    tt67wq
        6
    tt67wq  
       2018-08-07 09:07:38 +08:00
    数据结构挂科生
    frmongo
        7
    frmongo  
    OP
       2018-08-07 10:15:17 +08:00
    @tt67wq 确实挂科了,层主
    frmongo
        8
    frmongo  
    OP
       2018-08-07 10:19:25 +08:00
    @xpresslink sorry,语文也挂了..+_+
    frmongo
        9
    frmongo  
    OP
       2018-08-07 10:21:57 +08:00
    抱歉各位,py 基础不扎实,专门来碰钉子,我在 b = a.reverse()了一个 list 后,发现 b 是 none.
    总结了下,reverse()方法会修改原来的对象,[::-1]切片可以得到新的对象。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3251 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 12:12 · PVG 20:12 · LAX 05:12 · JFK 08:12
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.