我如何检查一个列表是否有任何重复,并返回一个没有重复的新列表?
当前回答
如果列表是有序的,则可以使用以下方法对其进行迭代,跳过重复的值。这对于处理内存消耗低的大列表特别有用,可以避免构建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]
其他回答
您可以通过使用集合简单地做到这一点。
步骤1:获取列表的不同元素 Step2获取列表的公共元素 3 .结合
In [1]: a = ["apples", "bananas", "cucumbers"]
In [2]: b = ["pears", "apples", "watermelons"]
In [3]: set(a).symmetric_difference(b).union(set(a).intersection(b))
Out[3]: {'apples', 'bananas', 'cucumbers', 'pears', 'watermelons'}
很晚才回答。 如果你不关心列表顺序,你可以使用*arg扩展集唯一性来删除dupes,即:
l = [*{*l}]
Python3演示
使用set:
a = [0,1,2,3,4,3,3,4]
a = list(set(a))
print a
使用unique:
import numpy as np
a = [0,1,2,3,4,3,3,4]
a = np.unique(a).tolist()
print a
Python内置了许多函数,您可以使用set()来删除列表中的重复项。 根据你的例子,下面有两个列表t和t2
t = ['a', 'b', 'c', 'd']
t2 = ['a', 'c', 'd']
result = list(set(t) - set(t2))
result
答:[b]
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)