我如何检查一个列表是否有任何重复,并返回一个没有重复的新列表?
当前回答
从列表中删除重复项的最佳方法是使用set()函数,该函数在python中可用,再次将该集合转换为列表
In [2]: some_list = ['a','a','v','v','v','c','c','d']
In [3]: list(set(some_list))
Out[3]: ['a', 'c', 'd', 'v']
其他回答
您可以比较集合和列表的长度,并将集合项保存到列表。
if len(t) != len(set(t)):
t = [x for x in set(t)]
>>> t = [1, 2, 3, 1, 2, 5, 6, 7, 8]
>>> t
[1, 2, 3, 1, 2, 5, 6, 7, 8]
>>> s = []
>>> for i in t:
if i not in s:
s.append(i)
>>> s
[1, 2, 3, 5, 6, 7, 8]
Python内置了许多函数,您可以使用set()来删除列表中的重复项。 根据你的例子,下面有两个列表t和t2
t = ['a', 'b', 'c', 'd']
t2 = ['a', 'c', 'd']
result = list(set(t) - set(t2))
result
答:[b]
您可以使用以下函数:
def rem_dupes(dup_list):
yooneeks = []
for elem in dup_list:
if elem not in yooneeks:
yooneeks.append(elem)
return yooneeks
例子:
my_list = ['this','is','a','list','with','dupicates','in', 'the', 'list']
用法:
rem_dupes(my_list)
[‘这个’,‘是’,‘“,“列表”,“与”,“dupicates”,“在”,“的”)
我的列表中有一个字典,所以我不能使用上面的方法。我得到了错误:
TypeError: unhashable type:
如果你关心顺序和/或某些项是不可散列的。那么你可能会发现这个很有用:
def make_unique(original_list):
unique_list = []
[unique_list.append(obj) for obj in original_list if obj not in unique_list]
return unique_list
有些人可能认为带副作用的列表理解不是一个好的解决方案。这里有一个替代方案:
def make_unique(original_list):
unique_list = []
map(lambda x: unique_list.append(x) if (x not in unique_list) else False, original_list)
return unique_list
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录