The problem of de-weight in python may be a simple question. For example a list:a = [1,3,2,9,5,3,1,5], how to remove duplicate elements, well, there is a high-end method: #方法一a = Set (a) A:1, 2, 3, 5, 9. Wow, good high-end, things are not so simple, observation, A's order changed, the type also changed print a, Type (a) set ([1, 2, 3, 5, 9]) <type ' Set ' >a becomes a collection type in Python, in order and without repeating elements, a bit similar to the function of sort, useful, However, the type of a that is changed by this method also changes the order of elements in a (although it is converted to a list type. Note that the elements in A are all numbers, if there are other elements in a, such as: a = [1,3,2,9,5,3,1,5,[1,2],[1,2]]print set (a) typeerror:unhashable type: ' List ' Then found that the set this method does not help, because there is an inside a non-hash element type, then what is a hash element? The Python document says so: An object ishashable if it has a hash value which never changes duringits lifetime (it needs a__hash__ () m Ethod), and can be compared to other objects (it needs an__eq__ () or __cmp__ () method). hashable objects which compare equal must has the same hash value. Meaning that the lifetime memory variable objects are not hashed, like List,dict is not hashed, because they are mutable objects, Tuple and Str are immutable objects, which are hashed. Therefore, the problem arises because the elements in the list cannot be assumed to be hashed, and this is not a common solution. # method Two look at another method, with a function. From collections Import Countera = [1,3,2,9,5,3,1,5]c = Counter (a) print C loses the result: Counter ({1:2, 3:2, 5:2, 2:1, 9:1}) that's good. , the number of each element in a is enumerated, so that it only needs to be based on the C elementThe corresponding number of elements to delete the repeating element (c is counter, you can see similar to the Dict type, usage is similar) c = {K:v-1 for k,v in C.items () if v > 1} #将a中元素个数大于1的元素找出来, V-1 indicates the number of duplicate elements to be deleted for k,v in C.items (): For I in range (v): #根据重复次数删除重复元素 A.remove (k) so that you can achieve the purpose of the weight, seems a bit complicated oh. See a Netizen with this method: A = sorted (set (a), key = A.index) Small and lean, very good oh but these methods also do not support the operation of non-hash objects, so this method is not universal. #方法三那只有最笨的方法了c = {A.count (a[i]): A[i] for I in Xrange (Len (a))} then apply method Two, in the process of applying this method, we find that the Dict type is key:value form, Where the value of key can only be a hash element, but also a new problem, and then read the Chen Ru write the Python source analysis, hehe! Not finished, to be continued ...
The problem of de-weight of list in Python