How to remove duplicates from a python list?

青灯夜游
Release: 2019-06-15 10:09:08
Original
13114 people have browsed it

How to remove duplicates from a python list? The following article will introduce to you how to remove duplicates from a python list. I hope it will be helpful to you. (Recommended learning: python video tutorial)

How to remove duplicates from a python list?

Python list deduplication method:

1. Use the loop search method

li = [1,2,3,3,4,2,3,4,5,6,1]
news_li = []
for i in li:
    if i not in news_li:
        news_li.append(i)
print (news_li)
Copy after login

Output:

[1, 2, 3, 4, 5, 6]
Copy after login
Copy after login

2. Use the set feature set()

li = [1,4,3,3,4,2,3,4,5,6,1]
new_li = list(set(li))
print (new_li)
Copy after login

Output:

[1, 2, 3, 4, 5, 6]
Copy after login
Copy after login

3. Use the grouby method of itertools module

import itertools
li = [1,4,3,3,4,2,3,4,5,6,1]
li.sort() #排序
it = itertools.groupby(li)
for k, g in it:
    print (k)
Copy after login

Output:

1
2
3
4
5
6
Copy after login

4. Use keys() method

li = [1,0,3,7,7,5]
formatli = list({}.fromkeys(li).keys())
print (formatli)
Copy after login

Output:

[1, 0, 3, 7, 5]
Copy after login

For more python related technical knowledge, please visit the python introductory tutorial column to learn!

The above is the detailed content of How to remove duplicates from a python list?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!