Order Changes in Set Conversions
When converting a list to a set in Python, the ordering of elements appears to be modified. This can be puzzling, as lists maintain the order of their elements, while sets are unordered data structures. The reason for this discrepancy lies in the fundamental nature of sets.
Sets are designed to perform efficient membership tests and do not retain the insertion order of elements. This is because sets are represented internally as hash tables, where elements are stored in a scrambled manner for faster lookup.
How to Preserve Order
If you require the preservation of order in your data collections, there are several alternatives to using sets:
B = set([6, 20, 1]) result = [x for x in A if x not in B]
import collections A = collections.OrderedDict.fromkeys([1, 2, 20, 6, 210]) B = collections.OrderedDict.fromkeys([6, 20, 1]) result = collections.OrderedDict.fromkeys(x for x in A if x not in B)
The above is the detailed content of Why Does Converting a List to a Set Change the Order, and How Can I Preserve It?. For more information, please follow other related articles on the PHP Chinese website!