I am having trouble figuring out why I make a set from a NumPy array, Python swaps the order of elements:
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
s by definition have no order - they are instead created so as to optimize certain operations such as those testing for containment. 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. Why do you care? Maybe a set is not what you need...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.