我如何检查一个列表是否有任何重复,并返回一个没有重复的新列表?
当前回答
如果列表是有序的,则可以使用以下方法对其进行迭代,跳过重复的值。这对于处理内存消耗低的大列表特别有用,可以避免构建dict或set的成本:
def uniq(iterator):
prev = None
for item in iterator:
if item != prev:
prev = item
yield item
然后:
for item in uniq([1, 1, 3, 5, 5, 6]):
print(item, end=' ')
输出将是:1 3 5 6
要返回一个列表对象,你可以这样做:
>>> print(list(uniq([1, 1, 3, 5, 5, 6])))
[1, 3, 5, 6]
其他回答
我用纯python函数做到了这一点。当您的项目值是JSON时,这是有效的。
[i for n, i in enumerate(items) if i not in items[n + 1 :]]
如果你不关心顺序,就这样做:
def remove_duplicates(l):
return list(set(l))
一个集合保证没有重复项。
我已将各种建议与perfplot进行了比较。事实证明,如果输入数组没有重复的元素,所有方法的速度或多或少都一样快,与输入数据是Python列表还是NumPy数组无关。
如果输入数组很大,但只包含一个唯一元素,则set、dict和np。如果输入数据是一个列表,唯一方法是常量时间的。如果是NumPy数组,np。Unique比其他选项快10倍。
让我有点惊讶的是这些也不是常时间运算。
代码重现图:
import perfplot
import numpy as np
import matplotlib.pyplot as plt
def setup_list(n):
# return list(np.random.permutation(np.arange(n)))
return [0] * n
def setup_np_array(n):
# return np.random.permutation(np.arange(n))
return np.zeros(n, dtype=int)
def list_set(data):
return list(set(data))
def numpy_unique(data):
return np.unique(data)
def list_dict(data):
return list(dict.fromkeys(data))
b = perfplot.bench(
setup=[
setup_list,
setup_list,
setup_list,
setup_np_array,
setup_np_array,
setup_np_array,
],
kernels=[list_set, numpy_unique, list_dict, list_set, numpy_unique, list_dict],
labels=[
"list(set(lst))",
"np.unique(lst)",
"list(dict(lst))",
"list(set(arr))",
"np.unique(arr)",
"list(dict(arr))",
],
n_range=[2 ** k for k in range(23)],
xlabel="len(array)",
equality_check=None,
)
# plt.title("input array = [0, 1, 2,..., n]")
plt.title("input array = [0, 0,..., 0]")
b.save("out.png")
b.show()
如果你不关心顺序,想要一些不同于上面建议的python方式(也就是说,它可以在面试中使用),那么:
def remove_dup(arr):
size = len(arr)
j = 0 # To store index of next unique element
for i in range(0, size-1):
# If current element is not equal
# to next element then store that
# current element
if(arr[i] != arr[i+1]):
arr[j] = arr[i]
j+=1
arr[j] = arr[size-1] # Store the last element as whether it is unique or repeated, it hasn't stored previously
return arr[0:j+1]
if __name__ == '__main__':
arr = [10, 10, 1, 1, 1, 3, 3, 4, 5, 6, 7, 8, 8, 9]
print(remove_dup(sorted(arr)))
时间复杂度:O(n)
辅助空间:O(n)
参考:http://www.geeksforgeeks.org/remove-duplicates-sorted-array/
Python 3中非常简单的方法:
>>> n = [1, 2, 3, 4, 1, 1]
>>> n
[1, 2, 3, 4, 1, 1]
>>> m = sorted(list(set(n)))
>>> m
[1, 2, 3, 4]