编程语言
首页 > 编程语言> > 【python-过滤列表中重复的数据】面试题 过滤给出的列表中重复的数据

【python-过滤列表中重复的数据】面试题 过滤给出的列表中重复的数据

作者:互联网

两种方法:

1,使用python自带列表去重函数set()

class Test_repeat():
def setup(self):
self.data=[1,2,3,4,1,5,6,3,1,7,7,7,7]
self.data_expect=[1, 2, 3, 4, 5, 6, 7]
def data_repeat(self,data:list):
data=set(data)
return list(data)
def test_repeat(self):
assert self.data_expect==self.data_repeat(self.data)
2,使用字典key的唯一性进行去重
class Test_repeat():
def setup(self):
self.data=[1,2,3,4,1,5,6,3,1,7,7,7,7]
self.data_expect=[1, 2, 3, 4, 5, 6, 7]
def data_repeat(self,data):
counter={}
for i in data:
if i not in counter.keys():
counter[i]=1
else:
counter[i]=+1
return list(counter.keys())
def test_repeat(self):
assert self.data_expect==self.data_repeat(self.data)

注:使用pytest习惯了 写法请轻喷

标签:repeat,重复,self,counter,列表,过滤,expect,data,def
来源: https://www.cnblogs.com/littlegoblin/p/16506637.html