Python list deduplication, Python list

Source: Internet
Author: User
Tags python list

Python list deduplication, Python list

Boring statistics on how many methods are available to deduplicate the list.

1. Set

list(set(alist))

To maintain the order:

import randomif __name__=='__main__':    a=[random.randint(0,10) for i in xrange(10)]    b=list(set(a))    b.sort(key=a.index)

2. Dictionary

Most of them use the hash table feature

{}.fromkeys(alist).keys()

Or manually write:

import randomif __name__=='__main__':    a=[random.randint(0,10) for i in xrange(10)]    d={}    for i in a:        d[i]=1    print d.keys()

3. Re-query after sorting

import randomif __name__=='__main__':    a=[random.randint(0,10) for i in xrange(10)]    a.sort()    print [x for i,x in enumerate(a) if not i or x!=a[i-1]]

4. itertools. groupby

import randomimport itertoolsif __name__=='__main__':    a=[random.randint(0,10) for i in xrange(10)]    a.sort()    print [x[0] for x in itertools.groupby(a)]

5. Traverse

import randomif __name__=='__main__':    a=[random.randint(0,10) for i in xrange(10)]    b=[]     for i in a:        if i not in b:            b.append(i)

Or use reduce:

import randomimport functoolsif __name__=='__main__':    a=[random.randint(0,10) for i in xrange(10)]    functools.reduce(lambda x,y:x if y in x else x+[y],[[],]+a)

Are there other methods?

 


Python removes duplicates from the list

List (set (l ))

Python list problems

List = ['my \ tname \ tis \ tandrew ']
New = list [0]. split ('\ t ')

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.