You are given a non-empty list of integers (X). For this task, you should return a list consisting of only the non-unique elements in this list. To do so you will need to remove all unique elements (elements which are contained in a given list only once). When solving this task, do not change the order of the list. Example: [1, 2, 3, 1, 3] 1 and 3 non-unique elements and result will be [1, 3, 1, 3].
翻译:
给您一个非空的整数列表(x)。对于此任务,您应该返回一个仅包含此列表中非唯一元素的列表。为此,需要删除所有唯一元素(仅包含在给定列表中一次的元素)。解决此任务时,不要更改列表的顺序。示例:[1、2、3、1、3]1和3个非唯一元素,结果将为[1、3、1、3]。
示例:
checkio([1, 2, 3, 1, 3]) == [1, 3, 1, 3] checkio([1, 2, 3, 4, 5]) == [] checkio([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5] checkio([10, 9, 10, 10, 9, 8]) == [10, 9, 10, 10, 9]
普通方法:
思路:去除列表中的唯一元素,我们能想到的是利用list中的.count()方法,统计出现次数大于1的元素
def checkio(data): result = [] for item in data: if data.count(item) > 1: result.append(item) return result
精简方法:
def checkio(data): data = list(i for i in data if data.count(i) > 1) return data
使用推导式可以使代码看起来很简洁