我如何检查一个列表是否有任何重复,并返回一个没有重复的新列表?
当前回答
我没有看到非哈希值的答案,一行,nlog n,标准库,所以这是我的答案:
list(map(operator.itemgetter(0), itertools.groupby(sorted(items))))
或作为一个生成函数:
def unique(items: Iterable[T]) -> Iterable[T]:
"""For unhashable items (can't use set to unique) with a partial order"""
yield from map(operator.itemgetter(0), itertools.groupby(sorted(items)))
其他回答
可以使用Python set或dict.fromkeys()方法删除重复项。 dict.fromkeys()方法将一个列表转换为一个字典。字典不能包含重复的值,因此dict.fromkeys()将返回只有唯一值的字典。 集,像字典一样,不能包含重复的值。如果将列表转换为集合,则删除所有重复项。
方法一:幼稚法
mylist = [5, 10, 15, 20, 3, 15, 25, 20, 30, 10, 100]
uniques = []
for i in mylist:
if i not in uniques:
uniques.append(i)
print(uniques)
方法二:使用set()
mylist = [5, 10, 15, 20, 3, 15, 25, 20, 30, 10, 100]
myset = set(mylist)
print(list(myset))
另一种做法:
>>> seq = [1,2,3,'a', 'a', 1,2]
>> dict.fromkeys(seq).keys()
['a', 1, 2, 3]
Write a Python program to create a list of numbers by taking input from the user and then remove the duplicates from the list. You can take input of non-zero numbers, with an appropriate prompt, from the user until the user enters a zero to create the list assuming that the numbers are non-zero.
Sample Input: [10, 34, 18, 10, 12, 34, 18, 20, 25, 20]
Output: [10, 34, 18, 12, 20, 25]
lst = []
print("ENTER ZERO NUMBER FOR EXIT !!!!!!!!!!!!")
print("ENTER LIST ELEMENTS :: ")
while True:
n = int(input())
if n == 0 :
print("!!!!!!!!!!! EXIT !!!!!!!!!!!!")
break
else :
lst.append(n)
print("LIST ELEMENR ARE :: ",lst)
#dup = set()
uniq = []
for x in lst:
if x not in uniq:
uniq.append(x)
# dup.add(x)
print("UNIQUE ELEMENTS IN LIST ARE :: ",uniq)
也有使用Pandas和Numpy的解决方案。它们都返回numpy数组,所以如果你想要一个列表,你必须使用.tolist()函数。
t=['a','a','b','b','b','c','c','c']
t2= ['c','c','b','b','b','a','a','a']
熊猫的解决方案
唯一使用Pandas函数():
import pandas as pd
pd.unique(t).tolist()
>>>['a','b','c']
pd.unique(t2).tolist()
>>>['c','b','a']
Numpy解决方案
使用numpy函数unique()。
import numpy as np
np.unique(t).tolist()
>>>['a','b','c']
np.unique(t2).tolist()
>>>['a','b','c']
注意,numpy.unique()也对值进行排序。所以列表t2是有序返回的。如果你想保留顺序,可以这样回答:
_, idx = np.unique(t2, return_index=True)
t2[np.sort(idx)].tolist()
>>>['c','b','a']
与其他解决方案相比,该解决方案并不那么优雅,但是,与pandas.unique()相比,numpy.unique()还允许您检查嵌套数组在选定的轴上是否唯一。
使用set,但保持顺序
unique = set()
[unique.add(n) or n for n in l if n not in unique]