The set function in python to deduplicate

The set function in python to deduplicate

The set() function is a relatively basic one of python's built-in functions. The main purpose is to create an unordered and non-repeated element set , which can perform relationship testing, delete duplicate data , and calculate intersection, difference, and union. Among them, set receives a list as a parameter.
For example:

li1=['a','b','c','d','a','b']
a=set()
for i in li:
    a.add(i)
print(a)
{
    
    'b', 'd', 'c', 'a'}

As above, after using the set() function to deduplicate the elements in the list, the elements in the list will become out of order. In this regard, if you want to keep the order of the deduplicated elements unchanged, you can use sort to reorder them in the original order.

li1=['a','b','c','d','a','b']
a=set()
for i in li:
    a.add(i)
a=list(a)#将set类型的转化为list类型
a.sort(key=li1.index) #按原来的序列排序
print(a)
['a', 'b', 'c', 'd']

Guess you like

Origin blog.csdn.net/weixin_57038791/article/details/129339447