awang
V2EX  ›  Python

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

By awang at 2014 年 9 月 22 日 · 6225 次点击
>>> 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 年 9 月 22 日
set是无序的
dorentus
   2
dorentus  
   2014 年 9 月 22 日   ❤️ 1
一般来说任何语言里面叫 set 和 dict 的数据结构都不保证顺序的。

https://docs.python.org/2/library/sets.html 这边的标题就写了 unordered:
8.7. sets — Unordered collections of unique elements
xiandao7997
   3
xiandao7997  
   2014 年 9 月 22 日
想回复的被1,2L说完了……速度真快
xiandao7997
   4
xiandao7997  
   2014 年 9 月 22 日   ❤️ 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 年 9 月 22 日   ❤️ 1
C++里面的set,map是红黑树(无序的是unordered_set,unordered_map,哈希实现).Java不太清楚,应该也有某个实现是红黑树的吧.
ren2881971
   6
ren2881971  
   2014 年 9 月 22 日
java里有 HashSet 和 TreeSet 都是无序的 只不过算法不一样。
好像还有一个记不清了。。
stackpop
   7
stackpop  
   2014 年 9 月 23 日
先理解什么是set, 什么是dict, 为什么有了list还需要set?
xinyewdz
   8
xinyewdz  
   2014 年 9 月 23 日
@ren2881971 Java里treeset是有序的,排过序。
ren2881971
   9
ren2881971  
   2014 年 9 月 23 日
@xinyewdz 好吧 学习了。 平时都用HashSet 真没用过TreeSet
推荐学习书目
› 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
© 2026 V2EX · 45ms · 3.9.8.5