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

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

  •  
  •   awang · 2014-09-22 17:18:43 +08:00 · 5215 次点击
    这是一个创建于 3509 天前的主题,其中的信息可能已经有所发展或是发生改变。
    >>> 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 条回复    2014-09-23 23:35:25 +08:00
    lnkisi
        1
    lnkisi  
       2014-09-22 17:22:07 +08:00
    set是无序的
    dorentus
        2
    dorentus  
       2014-09-22 17:23:07 +08:00   ❤️ 1
    一般来说任何语言里面叫 set 和 dict 的数据结构都不保证顺序的。

    https://docs.python.org/2/library/sets.html 这边的标题就写了 unordered:
    8.7. sets — Unordered collections of unique elements
    xiandao7997
        3
    xiandao7997  
       2014-09-22 17:26:00 +08:00
    想回复的被1,2L说完了……速度真快
    xiandao7997
        4
    xiandao7997  
       2014-09-22 17:26:45 +08:00   ❤️ 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  
       2014-09-22 19:34:27 +08:00   ❤️ 1
    C++里面的set,map是红黑树(无序的是unordered_set,unordered_map,哈希实现).Java不太清楚,应该也有某个实现是红黑树的吧.
    ren2881971
        6
    ren2881971  
       2014-09-22 22:31:15 +08:00
    java里有 HashSet 和 TreeSet 都是无序的 只不过算法不一样。
    好像还有一个记不清了。。
    stackpop
        7
    stackpop  
       2014-09-23 10:12:17 +08:00
    先理解什么是set, 什么是dict, 为什么有了list还需要set?
    xinyewdz
        8
    xinyewdz  
       2014-09-23 11:05:18 +08:00
    @ren2881971 Java里treeset是有序的,排过序。
    ren2881971
        9
    ren2881971  
       2014-09-23 23:35:25 +08:00
    @xinyewdz 好吧 学习了。 平时都用HashSet 真没用过TreeSet
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2202 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 02:14 · PVG 10:14 · LAX 19:14 · JFK 22:14
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.