Python implements method to remove duplicate elements from list

不言
Release: 2018-04-27 10:44:48
Original
2903 people have browsed it

This article mainly introduces Python's method of removing duplicate elements from a list. It summarizes and analyzes four implementation methods of Python list deduplication in the form of examples, involving Python's related operation skills such as list traversal, judgment, and sorting. Friends who need it can refer to

. The example of this article describes the method of removing duplicate elements from the list in Python. Share it with everyone for your reference. The details are as follows:

A total of four methods are used to remove duplicate elements in the list. The following is the specific implementation:

#!usr/bin/env python
#encoding:utf-8
'''
__Author__:沂水寒城
功能:去除列表中的重复元素
'''
def func1(one_list):
  '''''
  使用集合,个人最常用
  '''
  return list(set(one_list))
def func2(one_list):
  '''''
  使用字典的方式
  '''
  return {}.fromkeys(one_list).keys()
def func3(one_list):
  '''''
  使用列表推导的方式
  '''
  temp_list=[]
  for one in one_list:
    if one not in temp_list:
      temp_list.append(one)
  return temp_list
def func4(one_list):
  '''''
  使用排序的方法
  '''
  result_list=[]
  temp_list=sorted(one_list)
  i=0
  while i<len(temp_list):
    if temp_list[i] not in result_list:
      result_list.append(temp_list[i])
    else:
      i+=1
  return result_list
if __name__ == &#39;__main__&#39;:
  one_list=[56,7,4,23,56,9,0,56,12,3,56,34,45,5,6,56]
  print "脚本之家测试结果:"
  print func1(one_list)
  print func2(one_list)
  print func3(one_list)
  print func4(one_list)
Copy after login

The results are as follows:

Script House test results:
[0, 34, 3, 4, 5, 6, 7, 9, 12, 45, 23, 56 ]
[0, 34, 3, 4, 5, 6, 7, 9, 12, 45, 23, 56]
[56, 7, 4, 23, 9, 0, 12, 3, 34 , 45, 5, 6]
[0, 3, 4, 5, 6, 7, 9, 12, 23, 34, 45, 56]

Screenshot of running results:

Related recommendations:

Python example of deleting non-empty folders

Python implementation of library study Automatic room reservation function

Python Requests simulates login to realize automatic reservation of library seats


##

The above is the detailed content of Python implements method to remove duplicate elements from 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!