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

set 和 list 的顺序不一样,这是为什么?

  •  
  •   awang · Sep 22, 2014 · 5955 views
    This topic created in 4271 days ago, the information mentioned may be changed or developed.
    >>> M
    [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

    >>> [sum(row) for row in M]
    [6, 15, 24]
    >>> {sum(row) for row in M}
    set([24, 6, 15])
    9 replies    2014-09-23 23:35:25 +08:00
    lnkisi
        1
    lnkisi  
       Sep 22, 2014
    set是无序的
    dorentus
        2
    dorentus  
       Sep 22, 2014   ❤️ 1
    一般来说任何语言里面叫 set 和 dict 的数据结构都不保证顺序的。

    https://docs.python.org/2/library/sets.html 这边的标题就写了 unordered:
    8.7. sets — Unordered collections of unique elements
    xiandao7997
        3
    xiandao7997  
       Sep 22, 2014
    想回复的被1,2L说完了……速度真快
    xiandao7997
        4
    xiandao7997  
       Sep 22, 2014   ❤️ 1
    再搬运下:Like other collections, sets support x in set, len(set), and for x in set. Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior.
    chrishine
        5
    chrishine  
       Sep 22, 2014   ❤️ 1
    C++里面的set,map是红黑树(无序的是unordered_set,unordered_map,哈希实现).Java不太清楚,应该也有某个实现是红黑树的吧.
    ren2881971
        6
    ren2881971  
       Sep 22, 2014
    java里有 HashSet 和 TreeSet 都是无序的 只不过算法不一样。
    好像还有一个记不清了。。
    stackpop
        7
    stackpop  
       Sep 23, 2014
    先理解什么是set, 什么是dict, 为什么有了list还需要set?
    xinyewdz
        8
    xinyewdz  
       Sep 23, 2014
    @ren2881971 Java里treeset是有序的,排过序。
    ren2881971
        9
    ren2881971  
       Sep 23, 2014
    @xinyewdz 好吧 学习了。 平时都用HashSet 真没用过TreeSet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   982 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 20:37 · PVG 04:37 · LAX 13:37 · JFK 16:37
    ♥ Do have faith in what you're doing.