如何从列表python中删除唯一元素并保留一个重复?

时间:2021-01-10 12:36:47

标签: python python-3.x

编写一个程序,将一行中的数字列表作为输入,并在屏幕上的一行中显示其中多次出现的值。

输入:4 8 0 3 4 2 0 3(排序后:0 0 2 3 3 4 4 8)

输出:0 3 4

arr = list(map(int, input().split()))
arr.sort()
arr1 = list(dict.fromkeys(arr))
print(arr1)

2 个答案:

答案 0 :(得分:2)

你可以用集合来做到:

>>> s = [0, 0, 2, 3, 3, 4, 4, 8]
>>> {i for i in s if s.count(i) > 1}
{0, 3, 4}

现在,s.count 对于大型列表来说非常昂贵,因此您可以将计数存储在 O(n) 的 dict 中并使用它:

counts = {}
for i in s:
    counts[i] = counts.get(i, 0) + 1

>>> {i for i in s if counts[i] > 1}
{0, 3, 4}

答案 1 :(得分:0)

完全适合您的用例:

from itertools import groupby


arr = list(map(int, input().split()))
arr.sort()


print([key for key, group in groupby(arr) if len(list(group)) > 1])