我如何检查一个列表是否有任何重复,并返回一个没有重复的新列表?
当前回答
def remove_duplicates(input_list):
if input_list == []:
return []
#sort list from smallest to largest
input_list=sorted(input_list)
#initialize ouput list with first element of the sorted input list
output_list = [input_list[0]]
for item in input_list:
if item >output_list[-1]:
output_list.append(item)
return output_list
其他回答
使用set,但保持顺序
unique = set()
[unique.add(n) or n for n in l if n not in unique]
你也可以这样做:
>>> t = [1, 2, 3, 3, 2, 4, 5, 6]
>>> s = [x for i, x in enumerate(t) if i == t.index(x)]
>>> s
[1, 2, 3, 4, 5, 6]
上述工作的原因是index方法只返回元素的第一个索引。重复元素具有更高的下标。参考此处:
列表。索引(x[, start[, end]]) 的列表中返回从零开始的索引 如果没有,则引发ValueError异常 这样的项目。
如果你不关心顺序,就这样做:
def remove_duplicates(l):
return list(set(l))
一个集合保证没有重复项。
Python的魔力内置类型
在python中,仅通过python的内置类型就可以很容易地处理这样复杂的情况。
让我告诉你怎么做!
方法一:一般情况
方法(1行代码)删除重复的元素在列表中仍然保持排序顺序
line = [1, 2, 3, 1, 2, 5, 6, 7, 8]
new_line = sorted(set(line), key=line.index) # remove duplicated element
print(new_line)
你会得到结果的
[1, 2, 3, 5, 6, 7, 8]
方法二:特殊情况
TypeError: unhashable type: 'list'
处理不可哈希的特殊情况(3行代码)
line=[['16.4966155686595', '-27.59776154691', '52.3786295521147']
,['16.4966155686595', '-27.59776154691', '52.3786295521147']
,['17.6508629295574', '-27.143305738671', '47.534955022564']
,['17.6508629295574', '-27.143305738671', '47.534955022564']
,['18.8051102904552', '-26.688849930432', '42.6912804930134']
,['18.8051102904552', '-26.688849930432', '42.6912804930134']
,['19.5504702331098', '-26.205884452727', '37.7709192714727']
,['19.5504702331098', '-26.205884452727', '37.7709192714727']
,['20.2929416861422', '-25.722717575124', '32.8500163147157']
,['20.2929416861422', '-25.722717575124', '32.8500163147157']]
tuple_line = [tuple(pt) for pt in line] # convert list of list into list of tuple
tuple_new_line = sorted(set(tuple_line),key=tuple_line.index) # remove duplicated element
new_line = [list(t) for t in tuple_new_line] # convert list of tuple into list of list
print (new_line)
你会得到这样的结果:
[
['16.4966155686595', '-27.59776154691', '52.3786295521147'],
['17.6508629295574', '-27.143305738671', '47.534955022564'],
['18.8051102904552', '-26.688849930432', '42.6912804930134'],
['19.5504702331098', '-26.205884452727', '37.7709192714727'],
['20.2929416861422', '-25.722717575124', '32.8500163147157']
]
因为元组是可哈希的,你可以很容易地在列表和元组之间转换数据
如果你想保持顺序,不使用任何外部模块,这里有一个简单的方法:
>>> t = [1, 9, 2, 3, 4, 5, 3, 6, 7, 5, 8, 9]
>>> list(dict.fromkeys(t))
[1, 9, 2, 3, 4, 5, 6, 7, 8]
注意:这种方法保留了出现的顺序,因此,如上所示,9将在1之后,因为它是第一次出现。然而,这和你做的结果是一样的
from collections import OrderedDict
ulist=list(OrderedDict.fromkeys(l))
但它更短,跑得更快。
这是因为每次fromkeys函数尝试创建一个新键时,如果值已经存在,它就会简单地覆盖它。然而,这不会影响字典,因为fromkeys创建的字典中所有键的值都为None,因此有效地消除了所有重复的值。