简体   繁体   English

从NumPy数组订购python集

[英]Ordering of python set from NumPy array

I am having trouble figuring out why I make a set from a NumPy array, Python swaps the order of elements: 我无法弄清楚为什么我从NumPy数组中创建一个集合,Python交换了元素的顺序:

import numpy as np
A = np.array([2])
B = np.array([2, 8])
setA = set(A)
setB = set(B)

In [6]: A
Out[6]: [2]

In [7]: B
Out[7]: [2, 8]

In [8]: setA
Out[8]: set([2])

In [9]: setB
Out[9]: set([8, 2])

In [10]: list(setA.union(setB))
Out[10]: [8, 2]

In [11]: np.union1d(A,B).tolist()
Out[11]: [2, 8]

Why isn't the order wouldn't be maintained when I created set(B) ? 为什么创建set(B)时订单不会被维护?

set s by definition have no order - they are instead created so as to optimize certain operations such as those testing for containment. 根据定义, set s没有顺序 - 而是创建它们以便优化某些操作,例如那些测试包含的操作。 Therefore, you should never rely on order preservation when you create / add elements to a set. 因此,在创建/添加元素集时,不应该依赖于订单保留。

Sets are unordered collections of unique elements , so set([2,8]) and set([8, 2]) are exactly the same. 集合是唯一元素的无序集合 ,因此set([2,8])和set([8,2])完全相同。 Why do you care? 你为什么在乎? Maybe a set is not what you need... 也许一套不是你需要的......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM